IQueryable (non generic) : missing Count and Skip ? it works with IQueryable<T>

被刻印的时光 ゝ 提交于 2019-11-30 20:40:00
Jon Skeet

Well, quite simply those methods aren't available for IQueryable. If you look at the Queryable methods you'll see they're almost all based on IQueryable<T>.

If your data source will really be an IQueryable<T> at execution time, and you just don't know what T is, then you could find that out with reflection... or in C# 4, just use dynamic typing:

public static IQueryable GetPage(this IQueryable query,
     int page, int pageSize, out int count)
{
    int skip = (int)((page - 1) * pageSize);
    dynamic dynamicQuery = query;
    count = Queryable.Count(dynamicQuery);
    return Queryable.Take(Queryable.Skip(dynamicQuery, skip), pageSize);
}

The dynamic bit of the C# compiler will take care of working out T for you at execution time.

In general though, I'd encourage you to just try to use the generic form everywhere instead - it's likely to be significantly simpler.

The question is old but when someone needs the IQueryable extension methods then he/she should return IQueriable when the return type is anonymous.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!