Parallel LINQ -.Select () + .ForAll () returns fancy results

In life, I can’t understand why all the faces are not zero. I assume .ForAll() should be executed before I call the .All() method, but is it not?

 public class Foo { public string Bar { get; set; } } static void Main(string[] args) { var foos = new List<Foo> { new Foo(), new Foo(), new Foo() }; var newFoos = foos .AsParallel() .Select(x => { x.Bar = ""; return x; }); newFoos.ForAll(x => x = null); var allFoosAreNull = newFoos.All(x => x == null); Console.WriteLine(allFoosAreNull); // False ?? } 
+5
source share
1 answer

When you do it

 newFoos.ForAll(x => x = null); 

you assign null to x , which is the parameter of your lambda. x is local to lambda. This is not a ref parameter, and assigning values ​​to it has no effect outside of its body. Effectively this line does nothing.

+7
source

All Articles