简体   繁体   中英

Using LINQ for CSV data

My code works great, as long as there aren't any 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 still use LINQ to do this.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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