Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get from IQueryable to IEnumerable

Tags:

casting

f#

this should be a quick one for all you f# rockers, but it's got me stuck at the moment.

I've got an F# type which I'm trying to get to implement a c# interface

public interface ICrudService<T> where T: DelEntity, new()
{
    IEnumerable<T> GetAll();
}

here's how it's implemnted in c#:

public IEnumerable<T> GetAll()
{
    return repo.GetAll();
}

repo.GetAll returns an IQueryable, but the c# compiler knows enough to convert to IEnumerable because IQueryable<T> : IEnumerable<T>. but In F# the compiler can't work it and I've tried a few attempt to cast it correctly

type CrudService<'T when 'T :(new : unit -> 'T) and 'T :> DelEntity>(repo : IRepo<'T>) = 
    interface ICrudService<'T> with
         member this.GetAll () = 
            repo.GetAll<'T>

this is giving me a type mismatch error

like image 665
Jonny Cundall Avatar asked May 31 '14 17:05

Jonny Cundall


People also ask

Can we convert IQueryable to IEnumerable?

To cast IQueryable to IEnumerable, use the AsQueryable method. The AsQueryable method wraps the IEnumerable with IQueryable interface. That lets you build the expression tree without executing on the collection. Once you enumerate it, you get the same results.

Is IQueryable faster than IEnumerable?

IQueryable is faster than IEnumerable. In addition to Munesh Sharma's answer:IEnumerable loads data in-memory and then apply filters to it one by one but IQueryable apply filters all at once and return the result.

Should I use IQueryable or IEnumerable?

IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn't move between items, it is forward only collection. IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries).

What is the difference between returning IQueryable vs IEnumerable?

Both IEnumerable and IQueryable are forward collection. Querying data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data. Querying data from a database, IQueryable execute the select query on the server side with all filters.


1 Answers

You need to cast to IEnumerable<'T>:

type CrudService<'T when 'T :(new : unit -> 'T) and 'T :> DelEntity>(repo : IRepo<'T>) = 
        interface ICrudService<'T> with
             member this.GetAll () = 
                repo.GetAll() :> IEnumerable<'T>
like image 184
Lee Avatar answered Oct 22 '22 00:10

Lee