Reputation: 251
I have a list as the following, and I would like to add a "!" at the end of each element of the string list.
I know that I can easily achieve this by using the traditional foreach. I'm wondering how do I do it with list.ForEach()?
List<string> list = new List<string>();
list.Add("Hi");
list.Add("Hey");
list.Add("Cool");
list.Add("Nice Day");
I have tried this but it is not working for some reason.
list.ForEach(x => x += "!");
Thanks!
Upvotes: 0
Views: 7759
Reputation: 203802
First off, ForEach
is a method of List
, not a LINQ method.
Next, in your method there x
is a copy of the item in the list, and you're mutating that copy to add a !
to it, which is why the underlying list is unaffected.
LINQ is for querying data sources, so if you wanted to create an entirely new sequence/structure that has all of the strings that your list has, but with an exclamation at the end, you can use Select
for that:
var IMPORTANT = list.Select(s => s + "!");
If you want to mutate the items, just use a for
loop:
for(int i = 0; i < list.Count; i++)
list[i] += "!";
Note that if you tried to use a foreach
loop here, rather than a for
, you'd run into the exact same problem that you have with your ForEach
method. Consider this case:
foreach(var s in list)
s += "!";
Here s
is a copy of the item in the list. You're mutating the copy, leaving the item in the list unchanged. If your list contained mutatable data, rather than immutable data, you could mutate the item that the reference referred to, rather than mutating the reference itself and a foreach
or ForEach
would work fine.
Upvotes: 9