Lei Yang Lei Yang - 9 months ago 63
C# Question

Linq to trim each word in IList<string[]>

I know this question title is not precise, and there must be a better one, but my English is not so good. And also this question may be duplicate.
Now the task is read csv file, format like following:

col1, col2
int1, string1
int2, string2

Now I want to use Linq to parse to
, so it is easy for later use(each line convert to one object and there are many such csv files for various types). Code as following:

IList<string[]> v = File.ReadAllLines("test.csv").Select(
l => l.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries)
//if add this, cannot compile
//.Select(w => w.Trim())

Please help on the commented line. I want to trim each word, so that they can be converted to integers later. But this will not compile(I know the reason may be that Linq treats w as
, but how can I achieve my goal in only one Linq statement?

Answer Source

In your initial attempt you have an error in

l.Split(new char[] { ',', ',' } ...

since ', ' can't be a single character. You want something like this

IList<string[]> v = File
  .Skip(1) // skip titles
  .Select(line => line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
  .Select(items => items
    .Select(item => item.Trim()) // trim each item 

Edit: a shorter version suggested by Evk (see his comment below)

IList<string[]> v = File
  .Skip(1) // skip titles
  .Select(line => line
    .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    .Select(item => item.Trim()) // trim each item