How can I split and trim a string into parts all on one line?

Edward Tanguay picture Edward Tanguay · Nov 13, 2009 · Viewed 91.3k times · Source

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()); 

Answer

C&#233;dric Rup picture Cédric Rup · Nov 13, 2009

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