开发者

LINQ - Deferred Execution in Subqueries

My understanding is that the use of scalar or conversion functions causes immediate execution of a LINQ query. It is also my understanding that subqueries are executed开发者_如何学运维 upon demand of the outer query which would typically be once per element. For the following example would I be right in saying that the inner query is executed immediately? If so, as this would produce a scalar value how would this affect how the outer query operates?

IEnumerable<string> outerQuery = names.Where ( n => n.Length == names
                    .OrderBy(n2 => n2.Length).Select(n2 => n2.Length).First());

I would expect the above query to operate in a similar way as below, ie as if there wasn't a subquery.

int val = names.OrderBy(n2 => n2.Length).Select(n2 => n2.Length).First();

IEnumerable<string> outerQuery = names.Where ( n => n.Length == val );

This example was taken from Joseph and Ben Albahari's C# 4.0 in a Nutshell (Chp 8 P331/332) and my confusion stems from the accompanying diagram which appears to show that the subquery is being evaluated each time the outer query iterates through the elements of names.

Could someone clarify how LINQ works in this setup? Any help would be appreciated!


For the following example would I be right in saying that the inner query is executed immediately?

No, the inner query will be executed for each item in names when the outer query is enumerated. If you want it to be executed only once, use the second code sample.

EDIT: as LukeH pointed out, this is only true of Linq to Objects. Other Linq providers (Linq to SQL, Entity Framework...) might be able to optimize this automatically


What is names? If it's collection (and you use LINQ to Objects) then "subquery" will be executed for each outer query item. If it's actually query object then result depends on actual IQueryable.Provider. For example, for LINQ to SQL you will give SQL query with scalar subquery. And in the most cases subquery actually will be executed only once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜