Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trim all elements in a list?

Tags:

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?

like image 983
BrunoLM Avatar asked Aug 20 '10 13:08

BrunoLM


People also ask

How do I cut all elements in a list?

ForEach(x => x = x. Trim(). TrimStart().

How to trim all elements of a list in java?

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.


2 Answers

// 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, @"(?<=^|,) +| +(?=,|$)", ""); 
like image 62
LukeH Avatar answered Sep 27 '22 21:09

LukeH


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...

like image 32
CodingYourLife Avatar answered Sep 27 '22 21:09

CodingYourLife