Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
    
like image 511
Zaid Masud Avatar asked Feb 17 '23 04:02

Zaid Masud


1 Answers

  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.

like image 115
Kristian Fenn Avatar answered Mar 03 '23 08:03

Kristian Fenn