Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 651
Jan Carlo Viray Avatar asked Nov 28 '22 17:11

Jan Carlo Viray


2 Answers

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();
like image 108
Eric Lippert Avatar answered Dec 01 '22 07:12

Eric Lippert


Replace returns a new value, but doesn't affect the original String that you call it on. To do what you need, you'd have to build a new collection with the results from Replace - you can do this easily with Select:

var replaced = list.Select(i=>i.Replace(" ",String.Empty));

Another benefit, you won't need to cast to a List<T> to do this.

And as others have pointed out, you can use Trim() as a cleaner solution than Replace():

var collection = lastNames.Split(',').Select(i => i.Trim());
like image 30
PinnyM Avatar answered Dec 01 '22 05:12

PinnyM