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?
ForEach(x => x = x. Trim(). TrimStart().
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Parameter: It does not accepts any parameter. Return Value: It does not returns any value.
// 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, @"(?<=^|,) +| +(?=,|$)", "");
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With