Using LINQ for CSV Data

My code works fine if there are no commas in the data.

IEnumerable<Account> AccountItems = from line in File.ReadAllLines(filePath).Skip(1) let columns = line.Split(',') select new Account { AccountName = columns[0], BKAccountID = columns[1], Brand = columns[2], FirstOE = columns[3], LastOE = columns[4] }; 

But the output includes data with commas and wraps the data in double quotes when there is a comma in the data. I'm not sure if I can use LINQ for this.

 Acme Health Care,{C2F9A7DD-0000-0000-0000-8B06859016AD},"Data With, LLC",2/4/2013,2/18/2013 
+4
source share
1 answer

Take a look at this question: Reading CSV files using C #

 TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"); parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); while (!parser.EndOfData) { //Processing row string[] fields = parser.ReadFields(); foreach (string field in fields) { //TODO: Process field } } parser.Close(); 

No need to reinvent the wheel when .NET can hold your hand.

+7
source

All Articles