-3

I have a CSV which I want to import to a c# console application. I want to create arrays from each row of the CSV so I end up with a bunch of arrays, like the ones shown below (but would need to ignore the fisrt row if possible as it's a row of headings):

Array1 - [row2column1] [row2column2] [row2column3]
Array2 - [row3column1] [row3column2] [row3column3]
Array3 - [row4column1] [row4column2] [row4column3]

etc...

Is this possible? if so, how would i do this?

Thanks for the help

JNevill
  • 46,980
  • 4
  • 38
  • 63
Dylan
  • 1
  • 3
  • How about one [two-dimensional array](https://stackoverflow.com/questions/23292089/csv-file-contents-to-two-dimensional-array) or a [`List` of a class where the properties are the columns expected here](https://stackoverflow.com/questions/26790477/read-csv-to-list-of-objects) or read the CSV into a `datatable`. Creating `N` number of arrays dynamically based on the number of incoming lines doesn't sound like a good idea. Besides that, you just loop the file, split the line by whatever delimiter and load to whatever object (list of an object, multi-dim array, etc). – JNevill Nov 20 '18 at 21:36
  • What type of data, does this build a business entity? – Greg Nov 20 '18 at 21:39
  • 1
    There are too many 3rd party .NET CSV parsers to count. Just pick any of those that gives you acceptable perforamnce and results. For hte underlying datastructure, the options are jagged or 2 dimensional arrays. Personally I dislike the 2-dimensional style and always go for jagged. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays | https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays – Christopher Nov 20 '18 at 21:40

1 Answers1

2

You could use TextFieldParser. Each time you call ReadFields() it returns the next row of data as a string array. Do as you want with each array..

var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(@"C:\temp\test.csv");
parser.SetDelimiters(",");
parser.ReadFields(); // discard first row 
while (!parser.EndOfData)
{
    var array = parser.ReadFields(); // next row returned as an array of strings
}
einar
  • 56
  • 1
  • Nice, I did not know about this. Just include the Microsoft.VisualBasic.dll. Also see https://stackoverflow.com/questions/22297562/csv-text-file-parser-with-textfieldparser-malformedlineexception – Carlo Bos Nov 20 '18 at 22:30