Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diferences between IEnumerable<TSource> Where & IQueryable<TSource> Where extension methods

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?

like image 522
jlvaquero Avatar asked Dec 05 '25 19:12

jlvaquero


2 Answers

An IEnumerable is just a sequence of C# items. The IEnumerable version of Select literally just iterates, in C#, through the items in the input IEnumerable, 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.) The IQueryable version of Select can 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 IEnumerable version; if you're querying SQL via Linq-to-SQL, it'll use the IQueryable version.

like image 52
Rawling Avatar answered Dec 08 '25 07:12

Rawling


One works on IEnumerable<T>, the other one works on IQueryable<T>.

like image 38
O. R. Mapper Avatar answered Dec 08 '25 09:12

O. R. Mapper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!