看完this题, 我需要弄清楚一些事情。
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 子句并返回ONLY 相关行 - 而第二个查询执行 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;
现在的执行会有什么不同?
最佳答案
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>
兼容的任何内容
在这种情况下,第一个不会编译。
关于c# - IEnumerable<T> 和 IQueryable<T> 说明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11132888/