WTH is going in this code?
var ip = new double[] { 1, 2, 3 };
double sum = 0;
var output = ip.Select(w => sum += w);
var l1 = output.ToList(); //outputs 1,3,6
var l2 = output.ToList(); //7,9,12
8 Replies
You are committing a sin
Select shouldn't have side effects, it shouldn't mess with state
Each time you .ToList() you are running the loop that calls your select expression
You have some alternatives to select for these purposes. 1) Use .Sum() 2) Use .Aggregate()
Why did they make it this way?
What advantage do we get?
The lazy execution helps with performance, imagine it did all of the work and cached it into an array (js does this), what now if you just want the first record?
With LINQ that only will call your select expression once if you use .First() instead of .ToList()
With the JS way of doing things you just allocated a new array and threw away all of the values but the first
interesting..
I had forgotten about this.
IEnumerable<T> is lazy.
remembering this!It's just like us on that front
Only does the work if it has to
I thought we had
yield
for it?That's part of it, you can write your own generators with it
^yea kinda for like very big series for example. That's what I read.