C#将CSV添加到列表中

时间:2018-03-21 15:11:04

标签: c# list csv

我尝试将包含csv文件添加到新列表中。它是一个不同类型的人的列表,具有诸如函数,matricule,姓氏,名字和性别等特征。所以我设法阅读了该文件但我真的不知道如何处理以将该文件的包含添加到我的列表中。这是我的代码:

  `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>();

    }

&#39;

2 个答案:

答案 0 :(得分:1)

为什么不使用curl --request POST \ --url https://MYSERVICE.auth0.com/oauth/token \ --header 'content-type: application/json' \ --data '{"client_id":"MY_ID","client_secret":"MY_SECRET","audience":"TestApi","grant_type":"client_credentials"}' ,它将如下所示:

CSVHelper

你只需要安装nuget包:

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

}

查看this了解详情。

答案 1 :(得分:1)

用以下内容替换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); 

此外,如果Workers列表不是静态列表,则make ReadTest返回List并在函数内创建一个列表。

像这样:

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();

}