获取IQueryable< T> [英] Get count of an IQueryable<T>

查看:236
本文介绍了获取IQueryable< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下集合

 IEnumerable<int> list = new List<int> { 11, 12, 13, 14, 15, 16, 17, 18, 19, 10 };
 var query = list.Skip(5).Take(4);
 SomeMethod(query.AsQueryable()); 
 .
 .
 .
 public void SomeMethod(IQueryable<T> query)
 {
      var collectionCount = ?????  // count should be 10 not 4.
      ...
 }

如何在SomeMethod中获取查询的原始集合的计数(不应用Skip和Take子查询)。

How can I get the count of the original collection (without applying Skip and Take sub-queries) of the query in the SomeMethod.

谢谢。

推荐答案

没有办法获得信息(除了可能通过一些核心反射东西)。它根本不在那里了。这就像你想从这样的东西中提取原始计数:

There is no way you could get the information (except maybe by doing some hardcore reflection stuff). It is simply not there anymore. It’s like you wanted to extract the original count from something like this:

var list = new List<int> { 11, 12, 13, 14, 15, 16, 17, 18, 19, 10 };
SomeMethod(list[3]);

public void SomeMethod(int number)
{
  var collectionCount = ?????  // count should be 10
  ...
}

如果 IQueryable 可以传递 Expression ,则可能

每个评论已添加

这不是你想象的那么简单;我甚至不认为这是可能的完全一般。然而,对于一些有限的使用情况,它可能工作。我很快就黑了一个方法,删除任何跳过 a 采取应用于查询并返回原始计数。试试YMMV:

It is not as simple as you might think; I don’t even think it is possible fully generally. However, for some limited use cases it might work. I have quickly hacked a method which "removes" any Skip a Take applied to the query and returns the original count. Give it a try, YMMV:

public int CountOriginal<T>(IQueryable<T> query)
{
    var ex = query.Expression;
    while (ex.NodeType == ExpressionType.Call)
    {
        var call = (MethodCallExpression)ex;

        if (call.Method.Name != "Skip" && call.Method.Name != "Take") break;

        ex = call.Arguments[0];
    }
    var enumerable = Expression.Lambda(ex).Compile().DynamicInvoke(null) as IEnumerable<T>;
    if (enumerable == null) throw new NotImplementedException();
    return enumerable.Count();
}

这篇关于获取IQueryable&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆