例如:
var query = from c in db.Cars select c;
foreach(Car aCar in query)
{
Console.WriteLine(aCar.Name);
}
Run Code Online (Sandbox Code Playgroud)
编译后如何翻译?幕后发生了什么?
情况:假设我们正在执行连接两个内存列表的LINQ查询(因此不涉及DbSets或SQL查询生成),并且此查询也有一个where
子句.这where
仅过滤原始集合中包含的属性(from
查询的一部分).
问题: linq查询解释器是否优化了这个查询,因为它首先在执行where
之前执行join
,而不管我是where
在之前还是之后写的join
? - 所以它不必在以后不包含的元素上执行连接.
示例:例如,我有一个categories
列表,我想要与products
列表一起加入.但是,我只对category
with ID
1 感兴趣.无论我是否编写,linq解释器内部执行完全相同的操作:
from category in categories
join prod in products on category.ID equals prod.CategoryID
where category.ID == 1 // <------ below join
select new { Category = category.Name, Product = prod.Name };
Run Code Online (Sandbox Code Playgroud)
要么
from category in categories
where category.ID == 1 // <------ above join
join prod in products on category.ID …
Run Code Online (Sandbox Code Playgroud)