Is this fair to use a single lambda expression variable in multiple chained calls? For example:
MyList.Where(i => i.ID > 20).OrderBy(i => i.Name);
i used in
Where() remain independent of the
i used in
OrderBy() or can they have some hidden side-effects on each other, so that I must used different variable for each? Also, does your answer hold for VB.NET too?
I'm asking this because I have read in a slightly different context that I should not use foreach variable in LINQ queries directly and instead make a local copy of the variable inside the loop. Is there some similar effect hidden in the above code too?
Best How To :
Lambda expressions are basically a shorter way of writing anonymous methods. Therefore, the
i in your lambda examples is the same thing as a parameter in an anonymous method. In other words, they are independent of one another, just as parameters of different methods are independent of one another.
For the sake of readability, it may be worthwhile to change
person, or something similar. E.g.
MyList.Where(person => person.ID > 20).OrderBy(person => person.Name);
foreach: Read about closures in this context on Eric Lippert's blog: http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx
Because ()=>v means "return the current value of variable v", not "return the value v was back when the delegate was created". Closures close over variables, not over values. And when the methods run, clearly the last value that was assigned to v was 120, so it still has that value.