Macattackk
Macattackk

Reputation: 17

.ForEach() not applying while normal for loop is

Im trying to use the .ForEach() method to apply an action to a list but the action is not being applied. Here is an example of what I'm doing:

floatList.ForEach(f => f = 0);

This is not applying the action I'm doing within the lambda expression. When I do this same thing using a normal for loop, it executes correctly. I've tried looking up threads that explain the differences between the ForEach() method vs a normal foreach or for loop but I' m still not sure on why it is not executing the command I'm putting in within the .ForEach() method.

Upvotes: 0

Views: 93

Answers (2)

sstan
sstan

Reputation: 36483

Not sure what you are expecting exactly. I guess you would have to show us your "normal loop" to compare.

But your code is actually equivalent to:

foreach(float readOnlyF in floatList)
{
    float f = readOnlyF;
    f = 0;
}

It basically assigns a value to a local f variable, which you assign to, but that is immediately thrown away after the iteration completes. It doesn't try to write into the floatList, if that's what you were expecting.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The problem with assigning to f inside a lambda is that f is passed by value. Any changes to f itself are not reflected in the actual value in the collection or IEnumerable. foreach loop would have the same issue, except f would not be assignable. Regular for Loop, on the other hand, has a way to operate on the collection directly, so it is free of this problem.

Note that although changing the item itself is not allowed, you can call its mutable methods, and the changes would stay:

floatList.ForEach(f => f.SetSomeValue(0));

Upvotes: 3

Related Questions