Where is the ToList() method? (IQueryable)

六眼飞鱼酱① 提交于 2019-11-30 11:48:01

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;
}

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.

Here is an extension method for this:

public static class ListHelper
{
    public static IList ToList(this IQueryable query)
    {
        var genericToList = typeof(Enumerable).GetMethod("ToList")
            .MakeGenericMethod(new Type[] { query.ElementType });
        return (IList)genericToList.Invoke(null, new[] { query });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!