Reputation: 22814
If I have the following statement:
whatever.Select(x => collection.ToArray()[index]).ToList();
Is LINQ smart enough to perform the ToArray
cast only once (I'm not really aware of how this closure is transformed and evaluated)?
I understand that this code is bad, just interested.
Upvotes: 0
Views: 120
Reputation: 47048
You can have a peek at the code for LINQBridge, especially the Select
method (that ends up calling SelectYield
.
The essence of SelectYield
is a simple for-loop:
foreach (var item in source)
yield return selector(item, i++);
Where selector
is the lambda expression you pass in, in your case x => collection.ToArray()[index]
. From here it is obvious that the whole lambda expression will be evaluated for every element in whatever
.
Note that LINQBridge is a stand alone reimplementation of LINQ2Objects and thus not necessarily identical (but to a very large extent at least behaving exactly like LINQ2Objects, including side effects).
Upvotes: 0