繁体   English   中英

IEnumerable的 <T> 和IQueryable <T> 澄清?

[英]IEnumerable<T> and IQueryable<T> clarification?

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

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;

VS

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>兼容的任何内容

在这种情况下,第一个不会编译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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