Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand why the ForEach command isn't working

Tags:

c#

I am wanting to trim any white space off a collection of strings. I used the following code but it doesn't seem to work. Could anyone explain why?

result.ForEach(f => f = f.Trim());
like image 613
Mark Pearl Avatar asked Feb 02 '11 14:02

Mark Pearl


People also ask

Why foreach cannot break?

This finally brings us to the answer to our question, why can't we break out of a forEach() loop? It's because the loop is running that callback function over every item, so even if you write a return it's only returning on that instance of the function.

How to stop the forEach loop in c#?

Exit Foreach Loop Using break Keyword In C# Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.

What is the use of command foreach?

The foreach command implements a loop where the loop variable(s) take on values from one or more lists. In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script.

What can't foreach loops be used for?

For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time.


3 Answers

This won't work because you are assigning a new string reference to a local variable. This is probably what you are looking for:

result = result.Select(f => f.Trim()).ToList();
like image 184
ChaosPandion Avatar answered Oct 02 '22 13:10

ChaosPandion


You are re-assigning the argument variable inside the scope of the lambda. It's a collapsed form of:

foreach(string value in myList)
{
    Lambda(value);
}

void Lambda(string input)
{
    input = input.Trim();
}

The simplest way would probably be to use a projection:

myList = myList.Select(str => str.Trim()).ToList();
like image 37
Rex M Avatar answered Oct 02 '22 12:10

Rex M


foreach doesn't give you write access to the underlying collection, it only iterates through it, which means your change isn't stored back into the collection.

You can do two things:

  1. Produce a new collection

    var newResult = result.Select(f => f.Trim()).ToList();
    
  2. Use a normal for-loop and change the original collection

    for (int index = 0; index < result.Count; index++)
        result[index] = result[index].Trim();
    
like image 42
Lasse V. Karlsen Avatar answered Oct 02 '22 12:10

Lasse V. Karlsen