简体   繁体   中英

Read CSV file Linq

My data is as follows,

Name,Birthdate,Location,Qualification
"Ranjan,Priya",01/01/1988,"Pune,Maharashtra",B.Tech
"Mayank,Agrawal",05/05/1990,"Ranchi,Rajsthan",BCA

When i am using split property and comma as delimiter my name and location values gets splited but its a single value.Then how to get Name and Location as single value using linq.

Wouldn't really go with Linq on this one. RegEx is a much more natural fit and, bonus, this problem has been solved by others . That's where I found this:

  protected virtual string[] SplitCSV(string line)
  {         System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline) 
        | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
     Regex reg = new Regex("(?:^|,)(\\\"(?:[^\\\"]+|\\\"\\\")*\\\"|[^,]*)", options);
     MatchCollection coll = reg.Matches(line);
     string[] items = new string[coll.Count];
     int i = 0;
     foreach(Match m in coll)
     {
        items[i++] = m.Groups[0].Value.Trim('"').Trim(',').Trim('"').Trim();
     }
     return items;
  }

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