C#阅读从CSV文件中一个特定的值 [英] C# Read a particular value from CSV file

查看:218
本文介绍了C#阅读从CSV文件中一个特定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的学习者。我想读的CSV文件中一个特定的值。我已经学会了通过浏览的获​​取csv文件到一个DataTable。请参见下面的代码(感谢苏伦德拉JHA)和我的CSV文件格式。再说了,我想获得什么是ID= 90音量。



CSV文件

  ID:体积:名称
100:5600:一个
95:5000:乙
90:4500:C
85:4000:D

代码让所有的值:

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;使用System.Threading.Tasks
;
:使用System.IO;
使用System.Data这;
命名空间DVHConsolePrj
{
类节目
{
静态无效的主要(字串[] args)
{
readCsvFileData();
}
静态无效readCsvFileData()
{
路径字符串= @C:\IDVolumeName.txt
的StreamReader StreamReader的=新的StreamReader(路径);
数据表的数据表=新的DataTable();
INT行数= 0;
的String [] COLUMNNAME = NULL;
的String [] streamdatavalue = NULL;
,而(streamreader.EndOfStream!)
{
串streamrowdata = streamreader.ReadLine()修剪()。
如果(streamrowdata.Length大于0)
{
streamdatavalue = streamrowdata.Split(':');
如果(行数== 0)
{
行数= 1;
COLUMNNAME = streamdatavalue;
的foreach(在COLUMNNAME串csvheader)
{
的DataColumn的DataColumn =新的DataColumn(csvheader.ToUpper(),typeof运算(字符串));
datacolumn.DefaultValue =的String.Empty;
datatable.Columns.Add(DataColumn的);
}
}
,否则
{
DataRow的数据行= datatable.NewRow();
的for(int i = 0; I< columnname.Length;我++)
{
数据行[COLUMNNAME [I] = streamdatavalue [I] == NULL?的String.Empty:streamdatavalue [I]的ToString();
}
datatable.Rows.Add(数据行);
}
}
}
streamreader.Close();
streamreader.Dispose();
的foreach(在datatable.Rows的DataRow DR)
{
串rowvalues​​ =的String.Empty;
的foreach(在COLUMNNAME串csvcolumns)
{
rowvalues​​ + = csvcolumns +=+ DR [csvcolumns]的ToString()+;
}
Console.WriteLine(rowvalues​​);
}
到Console.ReadLine();
}
}
}


解决方案

相反在一个DataTable手动解析文件,然后做一些的LINQ,它直接使用Linq,使用的这个库



它工作得很好,是非常有效的大文件。



例如



1)添加的NuGet包在您的项目,下面一行是能够使用它。

 使用LINQtoCSV; 



2)定义类的年轻人中的数据

 公共类IdVolumeNameRow 
{
[CsvColumn(字段索引= 1)]
公共字符串ID {搞定;组; }

[CsvColumn(字段索引= 2)]
公共小数卷{搞定;组; }

[CsvColumn(字段索引= 3)
公共字符串名称{;组; }
}



3)和搜索的值

  VAR csvAttributes =新CsvFileDescription 
{
SeparatorChar =':',
FirstLineHasColumnNames = TRUE
};

变种CC =新CsvContext();

VAR体积= cc.Read< IdVolumeNameRow>(@C:\IDVolumeName.txt,csvAttributes)
。凡(I => i.ID ==90后 )
。选择(I => i.Volume)
.FirstOrDefault();


I am a learner in C#. I want to read a particular value from the CSV file. I have learned the getting the csv file into a datatable through browsing. Please see the following code (Thanks to surendra jha) and my CSV file format. Say, I want to get what is the 'Volume' for 'ID' = 90.

CSV file

ID:Volume:Name
100:5600:A
95:5000:B
90:4500:C
85:4000:D

Code for getting all the values:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;              
namespace DVHConsolePrj
{
   class Program
     {
       static void Main(string[] args)
         {
             readCsvFileData();
          }
        static void readCsvFileData()
         {            
            string path = @"C:\IDVolumeName.txt";           
            StreamReader streamreader = new StreamReader(path);
            DataTable datatable = new DataTable();
            int rowcount = 0;
            string[] columnname = null;
            string[] streamdatavalue = null;
            while (!streamreader.EndOfStream)
            {
               string streamrowdata = streamreader.ReadLine().Trim();
                 if (streamrowdata.Length > 0) 
                    {
                       streamdatavalue = streamrowdata.Split(':'); 
                       if (rowcount == 0)
                       {
                          rowcount = 1;
                          columnname = streamdatavalue;
                          foreach (string csvheader in columnname)
                          {
                             DataColumn datacolumn = new DataColumn(csvheader.ToUpper(), typeof(string));
                             datacolumn.DefaultValue = string.Empty;
                             datatable.Columns.Add(datacolumn);
                           }
                        }
                        else
                        {
                          DataRow datarow = datatable.NewRow();
                          for (int i = 0; i < columnname.Length; i++)
                          {
                           datarow[columnname[i]] = streamdatavalue[i] == null ?             string.Empty : streamdatavalue[i].ToString();
                           }
                           datatable.Rows.Add(datarow);
                         }
                   }
          }
          streamreader.Close();
          streamreader.Dispose();                         
          foreach (DataRow dr in datatable.Rows)
          {
              string rowvalues = string.Empty;
              foreach (string csvcolumns in columnname)
              {
                  rowvalues += csvcolumns + "=" + dr[csvcolumns].ToString() + "    ";
               }
              Console.WriteLine(rowvalues);
            }
           Console.ReadLine();
           }              
        }
     }

解决方案

Instead of parsing the file manually in a DataTable, then doing some Linq, use Linq directly on it, using this library.

It works pretty well and is very efficient with big files.

For instance.

1) Add nuget package in your project, and the following line to be able to use it:

using LINQtoCSV;

2) define the class that olds the data

public class IdVolumeNameRow
{
    [CsvColumn(FieldIndex = 1)]
    public string ID { get; set; }

    [CsvColumn(FieldIndex = 2)]
    public decimal Volume { get; set; }

    [CsvColumn(FieldIndex = 3)]
    public string Name{ get; set; }
}

3) and search for the value

    var csvAttributes = new CsvFileDescription
    {
        SeparatorChar = ':',
        FirstLineHasColumnNames = true
    };

    var cc = new CsvContext();

    var volume = cc.Read<IdVolumeNameRow>(@"C:\IDVolumeName.txt", csvAttributes)
            .Where(i => i.ID == "90")
            .Select(i => i.Volume)
            .FirstOrDefault();

这篇关于C#阅读从CSV文件中一个特定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆