简体   繁体   中英

C# Linq question

If I have the following statement:

whatever.Select(x => collection.ToArray()[index]).ToList();

So, is the 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 this code is bad, just interested.

不,它会在任何每个项目进行一次。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM