Let's say I need an extension method which selects only required properties from different sources. The source could be the database or in-memory collection. So I have defined such extension method:
public IQueryable<TResult> SelectDynamic<TResult>(
this IQueryable<T> source,
...)
This works fine for IQueryable
s. But, I have to call this function also for IEnumerable
s.
And in that case, I can call it with the help of .AsQueryable()
:
myEnumerable.AsQueryable()
.SelectDynamic(...)
.ToList();
Both work fine. And if both work fine, in which conditions I have to create two different extension methods for the same purpose, one for IEnumerable
and another one for IQueryable
?
My method has to send query to the database in case of Queryable
.
For example, here is the source of .Select
extension method inside System.Linq
namespace:
.Select
for IEnumerable.Select
for IQueryableI am repeating my main question again:
My method must send query to the database in case of Queryable
, but not when working with IEnumerable
. And for now, I am using AsQueryable()
for the enumerables. Because, I dont want to write same code for the Enumerable
. Can it have some side effects?
If your code only actually works when the objects its dealing with are loaded in memory, just supply the IEnumerable
variant and let your callers decide when they want to convert an IQueryable
into an in-memory IEnumerable
.
Generally, you won't implement new variations around IQueryable
unless you're writing a new database provider.
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