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

前端 未结 2 1370
灰色年华
灰色年华 2021-01-05 03:21

i have an extension method which a person was really helpful to give me... it does an orderby on IQueryable ... but i wanted one to do a normal IQueryable (non generic)

相关标签:
2条回答
  • 2021-01-05 03:59

    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.

    0 讨论(0)
  • 2021-01-05 04:17

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

    0 讨论(0)
提交回复
热议问题