C
C#3y ago
KidKai25

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
Bladesfist
Bladesfist3y ago
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()
KidKai25
KidKai25OP3y ago
Why did they make it this way? What advantage do we get?
Bladesfist
Bladesfist3y ago
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
KidKai25
KidKai25OP3y ago
interesting.. I had forgotten about this. IEnumerable<T> is lazy. remembering this!
Bladesfist
Bladesfist3y ago
It's just like us on that front Only does the work if it has to
KidKai25
KidKai25OP3y ago
I thought we had yield for it?
Bladesfist
Bladesfist3y ago
That's part of it, you can write your own generators with it
KidKai25
KidKai25OP3y ago
^yea kinda for like very big series for example. That's what I read.
Want results from more Discord servers?
Add your server