0
var arr = new[] {"A ", "B ", "C "}.ToList();
        arr.ForEach(a => a = a.Replace(" ", ""));

Why this does not remove space characters from the strings in the array?

This works arr = arr.Select(a => a.Replace(" ", "")).ToList();

6
  • 3
    ForEach does not modify the original collection, it only uses it as a source of inputs, your code is only updating the local variable to be without spaces, but those new values are not put back into the array. Commented Mar 30, 2020 at 9:45
  • arr = arr.Select(a => a.Replace(" ", "")).ToList(); Commented Mar 30, 2020 at 9:46
  • @DavidG Duh, sorry, I misread your code and mixed it up with the OPs proposal; arr = arr.Select(a => a.Replace(" ", "")) which is hideous. Sorry about that, you are not mutating anything, simply doing a projection and reassigning arr which is the right apporach. Commented Mar 30, 2020 at 10:01
  • 1
    @DavidG plus 3rd week in lock down :( I'm going bonkers... Commented Mar 30, 2020 at 10:03
  • The only thing about LINQ in your question is the .ToList(). The .ForEach method is just a method on List<>. Commented Mar 30, 2020 at 10:39

1 Answer 1

1

The problem is that a.Replace(..) returns a (reference to) a new string. You do assign that new reference back to the local parameter a. However, that parameter a is a copy of the reference in the list. Updating a does not update the reference in the list itself.

If you want to update "in place", you will have to do it the old fashioned way:

for (var i=0; i<arr.Count; i++)
{
    arr[i] = arr[i].Replace(" ", "");
}
Sign up to request clarification or add additional context in comments.

Comments

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.