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
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();
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With