Search code examples
foreachanonymous-methodsgeneric-list

Why does my attempt to trim strings in a List<string> not appear to work?


I tried the following code in LINQPad and got the results given below:

List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s) 
{ 
  s.Trim(); 
});
listFromSplit.Dump();

"a" and " b"

so the letter b didn't get the white-space removed as I was expecting...?

Anyone have any ideas

[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]


Solution

  • The String.Trim() method returns a string representing the updated string. It does not update the string object itself, but rather creates a new one.

    You could do this:

    s = s.Trim();
    

    However you cannot update a collection while enumerating through it so you'd want to either fill a new List while enumerating over the existing one or populate the List manually using the string array returned by String.Split.

    Filling a new list:

    List<string> temp = new List<string>("a, b".Split(",".ToCharArray()));
    List<string> listFromSplit = new List<string>();
    
    temp.ForEach(delegate(string s) 
    { 
        listFromSplit.Add(s.Trim()); 
    });
    
    listFromSplit.Dump();
    

    Populating Manually:

    string[] temp = "a, b".Split(",".ToCharArray());
    List<string> listFromSplit = new List<string>();
    
    foreach (string s in temp)
    {
        listFromSplit.Add(s.Trim()); 
    };
    
    listFromSplit.Dump();