tags:

views:

92

answers:

4

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  A: 
// 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, @"(?<=^|,) +| +(?=,|$)", "");
LukeH
This won't work the way he wants. The problem is that there is no comma between dddd and eeeee.
Justin Niessner
@Justin: Where does the OP say that this is a problem? As far as I can tell there should be four elements in the list: *"aaa"*, *"bbb"*, *"ccc"* and *"dddd eeeee"*.
LukeH
@LukeH - I kinda figured. And you're right. I read too much into and made an assumption.
Justin Niessner
That is exactly what I want.
BrunoLM
@Bruno: The elements in your `tags` list are references to the relevant strings. The `x` arguments passed into your delegate in the `ForEach` statement are *copies* of the references from the list, so when you assign the trimmed string back to `x`, you're replacing the *copy* of the reference, not the actual reference that's held in the list.
LukeH
+1  A: 

Your problem is that there is no comma between dddd and eeeee. If you want those to be separate, you need to split on ' ', strip the commas, and then trim extra whitespace.

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

var result = t1.Split(' ').Where(s => !String.IsNullOrEmpty())
                          .Select(s => s.Replace(',','').Trim())
                          .ToArray();
Justin Niessner
just remember to filter out all the empty elements after you split by space:tl.Split(' ').Select(s => s.Replace(",","").Trim()).Where(s => !string.IsNullOrEmpty(s)).ToArray()
theburningmonk
+4  A: 

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.

Lee
+3  A: 

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.

AllenG