Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the ToList() method? (IQueryable)

If I try this, it will work:

var query = myContextObject.Users.Where(u=>u.Name == "John");
query.ToList();

I'm able to call ToList and a lot of other extension methods.

But if I try this:

public List ConvertQueryToList(IQueryable query)
{
    return query.ToList();
}

ToList won't be accessible, I'm guessing this is because ToList is an extension method, but then how is that ToList is attached in the first example? Is it possible to access ToList in the second case?

like image 813
marcos.borunda Avatar asked Sep 03 '12 22:09

marcos.borunda


2 Answers

You need to write it as:

public List<T> ConvertQueryToList<T>(IQueryable<T> query)
{
    return query.ToList();
}

This will cause the IQueryable<T> to return the appropriate List<T>, since the Enumerable.ToList() method requires an IEnumerable<T> as input (which also works with IQueryable<T>, as IQueryable<T> inherits IEnumerable<T>).

That being said, there is really no reason to use it this way. You can always just call ToList() directly if you need to create a List<T> - abstracting inside of a second layer just confuses the API further.

If you're trying to convert a non-generic IQueryable interface, you would need to do something like:

public List<T> ConvertQueryToList<T>(IQueryable query)
{
    return query.Cast<T>.ToList();
}

This would then require calling like:

var results = ConvertQueryToList<SomeType>(queryable);

Alternatively, if you want to leave this non-generic (which I wouldn't recommend), then you could use:

public ArrayList ConvertQueryToList(IQueryable query)
{
    ArrayList results = new ArrayList();
    results.AddRange(query.Cast<object>().ToList());
    return results;
}
like image 90
Reed Copsey Avatar answered Oct 08 '22 23:10

Reed Copsey


The first of your examples returns an IQueryable<T>, whereas in the second you're using IQueryable (without the Generic Type parameter).

You can check out the two completely different interfaces here and here.

like image 20
Jon Egerton Avatar answered Oct 09 '22 00:10

Jon Egerton