IEnumerable 和IQueryable 澄清?

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

IQueryable custs = from c in db.Customers where c.City == "" select c; IEnumerable custs = from c in db.Customers where c.City == "" select c; 

问题:

1)可以这么说:在第一个查询中,SQLServer正在运行整个操作,包括where子句, 返回相关的行 – 而第二个查询执行SELECT * …并将所有行返回到C#和THENfilter?

2)如果我只有一个collections品 – 在记忆中怎么样? ( var lstMyPerson = new List()

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

VS

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

现在执行会有什么不同?

1:不,那是不正确的

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

您可以通过以下方式获得行为上的差异:

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

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

请注意:

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

与此不一样:

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

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

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

2: List没有为IQueryable实现或具有扩展方法,所涉及的LINQ操作符也不会返回与IQueryable兼容的任何内容

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