0

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.

1
  • 1
    ToArray() is a method call, not a cast. Commented Mar 31, 2011 at 9:58

2 Answers 2

7

No, it will be performed once for every item in whatever.

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.