gpt4 book ai didi

c# - 如何知道是否应用了 OrderBy 进行查询?

转载 作者:行者123 更新时间:2023-11-30 14:25:55 25 4
gpt4 key购买 nike

在应用 .Skip 或 .Take 之前,我需要知道是否将 OrderBy 应用于 Linq 查询。我无法控制接收到的查询,如果应用了 OrderBy,我需要维护这个,在任何其他情况下我应该 OrderBy(t=>true)。我尝试了以下方法:

    DataContext db;
var query = db.Orders;

var wasOrderByApplied = typeof(IOrderedQueryable<Order>).IsAssignableFrom(query.AsQueryable().Expression.Type);
var wasOrderByApplied2 = query.AsQueryable().Expression.Type == typeof(System.Data.Entity.Core.Objects.ObjectQuery<Order>);
var wasOrderByApplied3 = typeof(IOrderedQueryable<Order>) == query.AsQueryable().Expression.Type;

var query2 = db.Orders.OrderBy(o => o.CreationDate);

var wasOrderByApplied4 = typeof(IOrderedQueryable<Order>).IsAssignableFrom(query2.AsQueryable().Expression.Type);
var wasOrderByApplied5 = query2.AsQueryable().Expression.Type == typeof(System.Data.Entity.Core.Objects.ObjectQuery<Order>);
var wasOrderByApplied6 = typeof(IOrderedQueryable<Order>) == query2.AsQueryable().Expression.Type;

var query3 = db.Orders.OrderBy(o => o.CreationDate).Where(o => o.Id > 4);

var wasOrderByApplied7 = typeof(IOrderedQueryable<Order>).IsAssignableFrom(query3.AsQueryable().Expression.Type);
var wasOrderByApplied8 = query3.AsQueryable().Expression.Type == typeof(System.Data.Entity.Core.Objects.ObjectQuery<Order>);
var wasOrderByApplied9 = typeof(IOrderedQueryable<Order>) == query3.AsQueryable().Expression.Type;

结果:

wasOrderByApplied = true;
wasOrderByApplied2 = true;
wasOrderByApplied3 = false;

wasOrderByApplied4 = true;
wasOrderByApplied5 = false;
wasOrderByApplied6 = true;

根据最后的结果,似乎对每个查询提出的第三个问题是正确的,但后来我做了第三个查询 (query3),结果如下:

wasOrderByApplied7 = false;
wasOrderByApplied8 = false;
wasOrderByApplied9 = false;

当我在 OrderBy 之后添加 Where 时,问题结果是 false 而它应该是 true

是否有更好的方法来了解查询是否应用了 OrderBy?

最佳答案

这是我想到的一种可能的解决方案:

创建一个表达式访问者,检查表达式是否调用 OrderByOrderByDescending 方法,如下所示:

public class MyVisitor : ExpressionVisitor
{
public bool HasOrderBy { get; private set; }

protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.DeclaringType == typeof (Queryable) &&
(node.Method.Name == "OrderBy" || node.Method.Name == "OrderByDescending"))
HasOrderBy = true;

return base.VisitMethodCall(node);
}
}

这里是你如何使用它:

MyVisitor visitor = new MyVisitor();

visitor.Visit(query.Expression);

if (visitor.HasOrderBy)
{
//..
}
else
{
//..
}

关于c# - 如何知道是否应用了 OrderBy 进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com