What’s the diference between
public static IEnumerable<TSource> Where<TSource>
(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
and
public static IQueryable<TSource> Where<TSource>
(this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate)
Both methods can accept a lambda expression in the same way.
List<string> fruits =
new List<string> { "apple", "passionfruit", "banana", "mango",
"orange", "blueberry", "grape", "strawberry" };
IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);
Why delegate function and expresion of delegate function exists? Must I take care about it?
An
IEnumerableis just a sequence of C# items. TheIEnumerableversion ofSelectliterally just iterates, in C#, through the items in the inputIEnumerable, tests them against the delegate function, and yields those that match.An
IQueryable, however, can represent e.g. items in a SQL table. (Or many other kinds of data source, but SQL may be the most common.) TheIQueryableversion ofSelectcan convert the expression to part of an SQL query (or similar), and passes the burden of deciding which items to return back to the SQL server (or similar).You don’t really have to worry about this distinction – LINQ can hide all these details away for you. If you’re querying a list of C# objects, it’ll use the
IEnumerableversion; if you’re querying SQL via Linq-to-SQL, it’ll use theIQueryableversion.