Suppose I have a class which implements IQueryable<>
(which inherits IEnumerable<>
) interface.
When I call Where()
method on it, compiler resolves this call to IQueryable
extensions although IEnumerable
extensions also has Where()
method defined.
The question is how the compiler understands which extension should be called?
Thanks to LINQ, there’s almost no difference in how we construct queries against these two interfaces. To make it even more confused, IQueryable implements IEnumerable, and thus, results can be enumerated the same way regardless of which interface in use.
IEnumerable is best to query data from in-memory collections like List, Array, etc. While query data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data. IEnumerable is suitable for LINQ to Object and LINQ to XML queries. IEnumerable supports deferred execution.
IQueryable – intended to be run against a “queryable” collection (ex. a database). Lets take the following examples. When we have an in memory list, this Where LINQ statement is defined on the IEnumerable interface.
IQueryable is best to query data from out-memory (like remote database, service) collections. While query data from a database, IQueryable execute the select query on the server side with all filters. IQueryable is suitable for LINQ to SQL queries. IQueryable supports deferred execution.
C# spec has it described:
7.5.3.5 Better conversion target
Given two different types
T1
andT2
,T1
is a better conversion target thanT2
if at least one of the following holds:
An implicit conversion from
T1
toT2
exists, and no implicit conversion fromT2
toT1
exists
T1
is a signed integral type andT2
is an unsigned integral type.
Because there is a implicit conversion from IQueryable<T>
to IEnumerable<T>
, and there is no implicit conversion from IEnumerable<T>
to IQueryable<T>
, IQueryable<T>
is a better conversion target, and takes precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With