Zaid Masud
Zaid Masud

Reputation: 13453

How to convert IOrderedEnumerable to IOrderedQueryable

Invoking AsQueryable() on an IOrderedEnumerable invokes the extension method on IEnumerable and returns an IQueryable rather than IOrderedQueryable.

This doesn't really make sense to me. I would imagine that there should be an AsQueryable extension method on IOrderedEnumerable that returns IOrderedQueryable.

So my question has two parts:

  1. Should there be a public static IOrderedQueryable<TElement> AsQueryable<TElement>(this IOrderedEnumerable<TElement> source) extension method? If not, why?

  2. How would you currently convert a IOrderedEnumerable to IOrderedQueryable?

    IOrderedEnumerable<string> orderedEnumerable = new List<string>().OrderBy(s => s);
    
    IOrderedQueryable<string> orderedQueryable = // how can I convert orderedEnumerable here?
    

Upvotes: 5

Views: 8713

Answers (1)

Kristian Fenn
Kristian Fenn

Reputation: 867

  1. I honestly can't answer that question. The problem is AsQueryable() is defined on the IEnumerable interface, and overriding it might be an issue. You could probably define your own AsOrderedQueryable() extension reasonably easily.

  2. You have to apply the sorting after calling AsQueryable(). so new List<string>().AsQueryable().OrderBy(s => s); will return an IOrederedQueryable<string>.

EDIT: So in regards to your original question, you would write

IOrderedQueryable<string> orderedQueryable = orderedEnumerable.AsQueryable().OrderBy(s => s);

It's a little roundabout, but the relationship is that you turn an IEnumerable to an IOrderedEnumerable using OrderBy, and you change IQueryable to IOrderedQueryable via the same method. No direct method of conversion exists between IOrderedEnumerable and IOrderedQueryable AFAIK.

Upvotes: 8

Related Questions