0

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!

3
  • What's wrong with using the foreach? Commented Dec 16, 2013 at 18:49
  • 2
    List.ForEach is not LINQ. It's a .NET 2 method. Commented Dec 16, 2013 at 18:50
  • Nothing is wrong with the foreach, I'm just trying to learn the other way. Commented Dec 16, 2013 at 18:50

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@gleng Sprelling is hurd.
1
var newList = list.Select( x => x + "!" ).ToList()

3 Comments

While this works it is fundamentally different than ForEach. It has a void return type where Select does a projection and produces a new IEnumberable<T> (in this case T = string).
This reqires to create a new list via ToList which is less efficient than a simple for-loop.
And little bit about returning statements: visualstudiomagazine.com/articles/2012/02/01/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.