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

Because p.Trim() returns a new string.

You need to use:

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

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

Use the Select extension method instead:

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

After .net 5, the solution is as simple as:

List<string> parts = line.Split(';', StringSplitOptions.TrimEntries);

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

Tags:

C#

.Net

Split

Trim