tags:

views:

381

answers:

3

I want to split this line:

string line = "First Name ; string ; firstName";

into an array of their trimmed versions:

"First Name"
"string"
"firstName"

How can I do this all on one line? The following gives me an error "cannot convert type void":

List<string> parts = line.Split(';').ToList().ForEach(p => p.Trim());
+8  A: 

Try

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();

FYI, the Foreach method takes an Action (takes T and returns void) for parameter, and your lambda return a string as string.Trim return a string

Foreach extension method is meant to modify the state of objects within the collection. As string are immutable, this would have no effect

Hope it helps ;o)

Cédric

Cédric Rup
+3  A: 

The ForEach method doesn't return anything, so you can't assign that to a variable.

Use the Select exctension method instead:

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
Guffa
A: 

Because p.Trim() returns a new string.

You need to use:

List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
Matt Breckon