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

Solution 1:

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

Solution 2:

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

Solution 3:

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

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

Solution 4:

Because p.Trim() returns a new string.

You need to use:

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

Solution 5:

Here's an extension method...

    public static string[] SplitAndTrim(this string text, char separator)
    {
        if (string.IsNullOrWhiteSpace(text))
        {
            return null;
        }

        return text.Split(separator).Select(t => t.Trim()).ToArray();
    }