How can I trim all elements in a list?
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...
What's going on is that you're trying to modify a collection using a foreach
statement- which is a no-no. Collections cannot be modified with a foreach
.
You'll need to modifiy it a for
loop, or, using lambdas, you can use LukeH's solution.
The reason your approach doesn't work is that the x
is a copy of the current string reference being processed in the ForEach
call (i.e. local to the delegate). Therefore the assignment doesn't affect the item referenced in the list.
// you can omit the final ToArray call if you're using .NET 4
var result = string.Join(",", tl.Split(',').Select(s => s.Trim()).ToArray());
If you only need the final result string, rather than the intermediate collection, then you could use a regular expression to tidy the string. You'll need to benchmark to determine whether or not the regex outperforms the split-trim-join technique:
var result = Regex.Replace(tl, @"(?<=^|,) +| +(?=,|$)", "");