首页 > 解决方案 > 如何在具有动态条件的 linq 查询中使用 order by 子句?

问题描述

我需要一个连接多个表的 Linq 查询,并且需要动态使用具有条件的 order by 子句,该条件从 post 请求参数中获取。参数将是一个字符串值,需要附加在orderby条件中,例如orderBy(item.+conditon+)

 var x = db
   .table1
   .Join(db.table2,
         t1 => t1.id,
         t2 => t2.t2id,
         (t1,t2) => new{t1, t2})
   .Join(db.table3
         .....
   .Select(item => new {
       demo = item.t1.name
    })
   .OrderBy(item => item.+conditon+)



标签: c#linq

解决方案


假设要排序的可能字段数量有限(可能由数据库中索引的存在决定),您可能希望创建一个 switch case 来确定OrderBy参数,但您也可以使用动态表达式构建器创建它,例如这个:

public static void Execute(string[] args)
{
    var set = new[] { new { a = "a", b = 2 }, new { a = "b", b = 1 } };
    var orderby = GetOrderBy(set, "b");
    var orderedSet = set.OrderByDescending(orderby).ToList();
}

private static Func<T, object> GetOrderBy<T>(IEnumerable<T> set, string key)
{
    var sourceType = Expression.Parameter(typeof(T));
    var property = typeof(T).GetProperty(key) ?? throw new KeyNotFoundException($"Property {key} not found.");

    var body = Expression.Convert(Expression.Property(sourceType, property), typeof(object));

    var expression = Expression.Lambda(body, sourceType);

    return (Func<T, object>)expression.Compile();
}

我不确定你是否需要 aFunc<,>或 an Expression<Func<,>>OrderBy但如果你需要后者,你只需要删除 Compile 并更改返回类型。


推荐阅读