IQueryable vs IEnumerable...Extension Methods

716 views Asked by At

Seriously, I have to be missing something simple. Any help would be greatly appreciated.

Here is the scenario: 1) Create an IQueryable extension method called DoSomething with an appropriate signature (IQueryable, int x, int y). 2) Create an IEnumerable extension method called DoSomething using the same signature as the IQueryable, EXCEPT accepting/returning an IEnumerable instead of IQueryable. 3) Within the IEnumerable extension method, convert the enumerable to a Queryable (AsQueryable) and try to call the IQueryable.DoSomething method.

For some reason, the above scenario appears to make a recursive call to the IEnumerable extension method instead of the IQueryable. I don't understand why.

I understand that IQueryable extends IEnumerable; however, the .NET extensions seem to detect and work correctly. For example, variable.AsQueryable().Take(1) will, at least via the intellisense (and ReSharper), call the Queryable extension, not the Enumerable extension. When I write my own, it does not appear to work and an infinite loop is created.

1

There are 1 answers

0
DannyMeister On

I believe the answer is that it works as you described just fine. Here's my little LINQPad test program. Admittedly, this scenario is slightly simpler than the one you describe because I return void and take no parameters.

void Main()
{
    int[] numbers = { 1, 2, 3, 4, 5 };
    numbers.AsQueryable().DumpLast<int>();
    numbers.DumpLast<int>();
}

public static class TestExtensions
{
    public static void DumpLast<T>(this IQueryable<T> list)
    {
        list.Last<T>().Dump();
    }

    public static void DumpLast<T>(this IEnumerable<T> list)
    {
        list.AsQueryable().DumpLast<T>();
    }
}

Output:

5
5

If you can provide a more concrete example then maybe there's something we could spot that is causing an issue.