The ForEach Replace on this small code doesn't do what I expected it to do. What am I doing wrong here?

c#, linqpad, replace

Solution

As others have pointed out, strings are immutable. Calling Replace simply returns a new string; it does not mutate the existing string in place. Here are three ways to do what you want:

Do the transformation on the sequence, and convert it to a list at the end:

string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";  
List<string> lastNames = s.Split(',').Select(x=>x.Trim()).ToList();

Or, the same thing in query syntax:

string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN"; 
var query = from lastName in s.Split(',')
            select lastName.Trim();
List<string> lastNames = query.ToList();

Or, make an array and mutate the array in place:

string s = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN";  
string[] lastNames = s.Split(',');
for (int i = 0; i < lastNames.Length; ++i)
    lastNames[i] = lastNames[i].Trim();

Problem

I don't know if this is LINQPad-related or I'm doing something wrong, but this code doesn't do what I want it to do, specifically the `ForEach(...)` My goal is to replace the " " with an empty string; is there a better way to do this? ``` var lastNames = "SMITH, JOHNSON, WILLIAMS, JONES, BROWN"; var listLastNames = lastNames.Split(','); var list = listLastNames.ToList(); //so I can use .ForEach list.ForEach(i=>i.Replace(" ",String.Empty)); list.Dump(); //show it on output ```

Original source