Importing CSV data into C# classes

前端 未结 7 1363
广开言路
广开言路 2020-12-02 01:45

I know how to read and display a line of a .csv file. Now I would like to parse that file, store its contents in arrays, and use those arrays as values for some classes I cr

7条回答
  •  悲哀的现实
    2020-12-02 02:25

    Linq also has a solution for this and you can define your output as either a List or an Array. In the example below there is a class that as the definition of the data and data types.

    var modelData = File.ReadAllLines(dataFile)
                       .Skip(1)
                       .Select(x => x.Split(','))
                       .Select(dataRow => new TestModel
                       {
                           Column1 = dataRow[0],
                           Column2 = dataRow[1],
                           Column3 = dataRow[2],
                           Column4 = dataRow[3]
                       }).ToList(); // Or you can use .ToArray()
    

提交回复
热议问题