IQueryable 和 IEnumerable 有什么区别 [英] What's the difference between IQueryable and IEnumerable

查看:21
本文介绍了IQueryable 和 IEnumerable 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对差异感到困惑.作为 .Net 的新手,我知道我可以使用 Linq 扩展查询 IEnumerables.那么这个 IQueryable 是什么,它有什么不同?

I'm confused as to the difference. Being fairly new to .Net, I know I can query IEnumerables using the Linq extensions. So what is this IQueryable and how does it differ?

另见 IQueryable 有什么区别[T]和 IEnumerable[T]? 与这个问题重叠.

See also What is the difference between IQueryable[T] and IEnumerable[T]? that overlaps with this question.

推荐答案

IEnumerable 表示 T 的只进游标..NET 3.5 添加了包含 LINQ 标准查询运算符 的扩展方法,例如 WhereFirst,任何需要谓词或匿名函数的运算符都采用 Func.

IEnumerable<T> represents a forward-only cursor of T. .NET 3.5 added extension methods that included the LINQ standard query operators like Where and First, with any operators that require predicates or anonymous functions taking Func<T>.

IQueryable 实现相同的 LINQ 标准查询运算符,但接受 Expression> 用于谓词和匿名函数.Expression 是一个编译后的表达式树,是该方法的分解版本(半编译",如果你愿意的话),它可以被可查询的提供者解析并相应地使用.

IQueryable<T> implements the same LINQ standard query operators, but accepts Expression<Func<T>> for predicates and anonymous functions. Expression<T> is a compiled expression tree, a broken-up version of the method ("half-compiled" if you will) that can be parsed by the queryable's provider and used accordingly.

例如:

IEnumerable<Person> people = GetEnumerablePeople();
Person person = people.Where(x => x.Age > 18).FirstOrDefault();

IQueryable<Person> people = GetQueryablePeople();
Person person = people.Where(x => x.Age > 18).FirstOrDefault();

在第一个块中,x =>x. 年龄 >18 是一个匿名方法(Func),它可以像任何其他方法一样执行.Enumerable.Where 将为每个人执行一次该方法,产生方法返回true的值.

In the first block, x => x.Age > 18 is an anonymous method (Func<Person, bool>), which can be executed like any other method. Enumerable.Where will execute the method once for each person, yielding values for which the method returned true.

在第二个块中,x =>x. 年龄 >18 是一个表达式树(Expression>),可以认为是是'Age'属性> 18".

In the second block, x => x.Age > 18 is an expression tree (Expression<Func<Person, bool>>), which can be thought of as "is the 'Age' property > 18".

这允许诸如 LINQ-to-SQL 之类的东西存在,因为它们可以解析表达式树并将其转换为等效的 SQL.并且因为提供者不需要在枚举 IQueryable 之前执行(毕竟它实现了 IEnumerable),所以它可以组合多个查询运算符(在上面的示例 WhereFirstOrDefault) 以更明智地选择如何针对底层数据源执行整个查询(例如使用 SELECT TOP 1SQL).

This allows things like LINQ-to-SQL to exist because they can parse the expression tree and convert it into equivalent SQL. And because the provider doesn't need to execute until the IQueryable is enumerated (it implements IEnumerable<T>, after all), it can combine multiple query operators (in the above example Where and FirstOrDefault) to make smarter choices on how to execute the entire query against the underlying data source (like using SELECT TOP 1 in SQL).

见:

这篇关于IQueryable 和 IEnumerable 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆