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?
You need to write it as:
This will cause the
IQueryable<T>to return the appropriateList<T>, since theEnumerable.ToList()method requires anIEnumerable<T>as input (which also works withIQueryable<T>, asIQueryable<T>inheritsIEnumerable<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 aList<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:
This would then require calling like:
Alternatively, if you want to leave this non-generic (which I wouldn’t recommend), then you could use: