简体   繁体   English

C#将CSV添加到列表

[英]C# Adding CSV to a list

I try to add the containing of a csv file to a new list. 我尝试将包含CSV文件的文件添加到新列表中。 It's a list of different types of people with caracteristics like the function, a matricule, the last name, the firstname and a sex. 这是具有特征的不同类型的人的列表,例如功能,矩阵,姓,名和性别。 So I managed to read the file but I don't really know how to process to add the containing of the file to my list.Here is my code : 所以我设法读取了文件,但我真的不知道如何处理将文件的内容添加到列表中,这是我的代码:

  `private static void ReadTest() 
    {
        int count = 0;
        string line;
        Char c = ';';

        StreamReader file= new StreamReader("Listing.csv");

        while ((line= file.ReadLine()) != null)
        {
            String[] substrings = line.Split(c);

            foreach (var substring in substrings)
            {
                Console.WriteLine(substring);
            }

            count++;
        }

        fichier.Close();
        System.Console.WriteLine("Number of lines : {0}.", count);
    }
    static void Main(string[] args)
    {
        List<Personnel> Workers = new List<Personnel>();

    }

' '

Why don't you use CSVHelper , it will be as simple as the following: 您为什么不使用CSVHelper ,它就像下面这样简单:

var csv = new CsvReader( textReader );
var records = csv.GetRecords<Personnel>();
//then loop through
foreach( var record in records )
{

}

you just need to install the nuget package: 您只需要安装nuget软件包:

Install-Package CsvHelper

Check this for more information. 检查以获取更多信息。

Replace the foreach loop with something like the following: 用以下内容替换foreach循环:

var person = new Personnel(); 
person.firstname = substrings[0];
person.lastname = substrings[1]; 
person.function = substrings[2]; 
//continue until all variables assigned. 
Workers.Add(person); 

Also, if the Workers list is not a static list, then make ReadTest return a List and create a list within the function. 另外,如果Workers列表不是静态列表,则使ReadTest返回一个List并在函数内创建一个列表。

Like this: 像这样:

private static List<Personnel> ReadTest() 
{
    int count = 0;
    string line;
    Char c = ';';

    StreamReader file= new StreamReader("Listing.csv");
    var Workers = new List<Personnel>();

    while ((line= file.ReadLine()) != null)
    {
        String[] substrings = line.Split(c);

        var person = new Personnel(); 
        person.firstname = substrings[0];
        person.lastname = substrings[1]; 
        person.function = substrings[2]; 
        //continue until all variables assigned. 
        Workers.Add(person); 

        count++;
    }

    file.Close();
    System.Console.WriteLine("Number of lines : {0}.", count);
    return Workers; 
}
static void Main(string[] args)
{
    List<Personnel> Workers = ReadTest();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM