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?
See also What is the difference between IQueryable[T] and IEnumerable[T]? that overlaps with this question.
IEnumerable<T>represents a forward-only cursor ofT. .NET 3.5 added extension methods that included theLINQ standard query operatorslikeWhereandFirst, with any operators that require predicates or anonymous functions takingFunc<T>.IQueryable<T>implements the same LINQ standard query operators, but acceptsExpression<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.For example:
In the first block,
x => x.Age > 18is an anonymous method (Func<Person, bool>), which can be executed like any other method.Enumerable.Wherewill execute the method once for each person,yielding values for which the method returnedtrue.In the second block,
x => x.Age > 18is an expression tree (Expression<Func<Person, bool>>), which can be thought of as “is the ‘Age’ property > 18”.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
IQueryableis enumerated (it implementsIEnumerable<T>, after all), it can combine multiple query operators (in the above exampleWhereandFirstOrDefault) to make smarter choices on how to execute the entire query against the underlying data source (like usingSELECT TOP 1in SQL).See: