Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Generic AsEnumerable

Tags:

c#

linq

How would you suggest using AsEnumerable on a non-generic IQueryable?

I cannot use the Cast<T> or OfType<T> methods to get an IQueryable<object> before calling AsEnumerable, since these methods have their own explicit translation by the underlying IQueryProvider and will break the query translation if I use them with a non-mapped entity (obviously object is not mapped).

Right now, I have my own extension method for this (below), but I'm wondering if there's a way built into the framework.

public static IEnumerable AsEnumerable(this IQueryable queryable)
{
    foreach (var item in queryable)
    {
        yield return item;
    }
}

So, with the above extension method, I can now do:

IQueryable myQuery = // some query...

// this uses the built in AsEnumerable, but breaks the IQueryable's provider because object is not mapped to the underlying datasource (and cannot be)
var result = myQuery.Cast<object>().AsEnumerable().Select(x => ....);

// this works (and uses the extension method defined above), but I'm wondering if there's a way in the framework to accomplish this
var result = myQuery.AsEnumerable().Cast<object>().Select(x => ...);
like image 299
Jeff Avatar asked Dec 04 '25 15:12

Jeff


2 Answers

Since the interface IQueryable inherits from IEnumerable why not:

IQueryable queryable;
IEnumerable<T> = (queryable as IEnumerable).Cast<T>();

Edit
There are two Cast<> extension methods:

public static IQueryable<TResult> Cast<TResult>(this IQueryable source)
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)

Which one is called is statically decided by the compiler. So casting an IQueryable as an IEnumerable will cause the second extension method to be called, where it will be treated as an IEnumerable.

like image 52
Greg Avatar answered Dec 07 '25 03:12

Greg


JaredPar's answer in other words:

public static IEnumerable AsEnumerable(this IEnumerable source)
{
    return source;
}

Usage:

IQueryable queryable = // ...
IEnumerable enumerable = queryable.AsEnumerable();
IEnumerable<Foo> result = enumerable.Cast<Foo>();
//                                     ↑
//                           Enumerable.Cast<TResult>(this IEnumerable source)
like image 26
dtb Avatar answered Dec 07 '25 05:12

dtb