且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取IQueryable< T>

更新时间:2022-03-13 15:02:47

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

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