17

读完这个问题后,我需要澄清一些事情。

IQueryable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

IEnumerable<Customer> custs = from c in db.Customers
where c.City == "<City>"
select c;

问题:

1) 可以这样说:在第一个查询中,SQLServer 正在运行整个操作,包括 where 子句并返回相关行 - 而第二个查询SELECT *...并将 所有 行返回到 C# 和THEN过滤器?

2)如果我只有一个集合——在内存中怎么办。( var lstMyPerson = new List<MyPerson>())

IQueryable<MyPerson> lst = from c in lstMyPerson 
where c.City == "<City>"
select c;

对比

IEnumerable<MyPerson> custs = from c in lstMyPerson 
where c.City == "<City>"
select c;

现在执行会有什么不同?

4

1 回答 1

34

1:不,这是不正确的

由于您只是结果存储到 中IEnumerable<Customer>,但仍然具有产生结果的完全相同的表达式,因此它们都将在服务器上执行并仅返回相关行。

你会得到这样的行为差异:

IEnumerable<Customer> custs = from c in (IEnumerable<Customer>)db.Customers
    where c. City == "<City>"
    select c;

在这种情况下,您强制将db.Customers集合用作IEnumerable<T>,枚举时将获取整个集合。

请注意:

IEnumerable<Customer> x = from c in db.Customers
                          where c.City == "<City>"
                          select c;

与此不同:

IEnumerable<Customer> x = from c in db.Customers
                          select c;
IEnumerable<Customer> y = x.Where(c => c.City == "<City>");

在第一种情况下,where子句将成为 SQL 的一部分,而在第二种情况下则不会。这就是为什么链接的问题/答案涉及差异,而您的代码没有。

另请注意,只有您编写的语句实际上不会在服务器上执行任何操作,因为它们实际上只会存储惰性集合。如果您继续枚举这些集合,那么相关位将在服务器上执行。

2:List<T>没有实现或具有扩展方法IQueryable<T>,涉及的 LINQ 运算符也不会返回任何与IQueryable<T>

在这种情况下,第一个将无法编译。

于 2012-06-21T06:52:13.083 回答