How can I trim all elements in a list?

Viewed 30603

I'm trying the following

string tl = " aaa, bbb, ccc, dddd             eeeee";

var tags = new List<string>();
tags.AddRange(tl.Split(','));
tags.ForEach(x => x = x.Trim().TrimStart().TrimEnd());

var result = String.Join(",", tags.ToArray());

But it doesn't work, the tags always come back as " aaa", " bbb".

How can I trim all elements in a list?

6 Answers

Ran into the same problem. @Lee already explained that Lamda .ForEach() uses a copy.

You can write an Extension Method like this and use a for loop (foreach also not possible):

public static class StringListExtensions
{
    public static void TrimAll(this List<string> stringList)
    {
        for (int i = 0; i < stringList.Count; i++)
        {
            stringList[i] = stringList[i].Trim(); //warning: do not change this to lambda expression (.ForEach() uses a copy)
        }
    }
}

Use it like this:

var productNumbers = new List<string>(){ "11111", " 22222 " }
productNumbers.TrimAll();

should result in: List(){ "11111", "22222" }

I didn't use the split and re-join solution (chosen solution) because there can be a comma inside one of the string items. The regex version is not self explanatory. This is old-school but safer and can be easily understood...

Try

List<string> lstSelect = string_test.Split(',').Select(x => x.Trim()).ToList();
Related