Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases do I need to create two different extension methods for IEnumerable and IQueryable?

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 IQueryables. But, I have to call this function also for IEnumerables.

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 IQueryable

I 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?

like image 267
Farhad Jabiyev Avatar asked Jun 18 '15 07:06

Farhad Jabiyev


1 Answers

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.

like image 101
Damien_The_Unbeliever Avatar answered Oct 18 '22 08:10

Damien_The_Unbeliever