c# - 如何在具有动态条件的 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+)
解决方案
假设要排序的可能字段数量有限(可能由数据库中索引的存在决定),您可能希望创建一个 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 并更改返回类型。
推荐阅读
- angular - 集成测试 ReactiveForm,valueChanges 方法未触发
- macos - 在 mac os x 中运行 crontab 任务时未绑定的变量
- php - PHP 警告:foreach() 提供的参数 2 和无效参数
- python - pyppeteer - 如何通过使用 python pyppeteer 在页面中单击子链接 (href) 转到下一页
- android - 如何在物理设备上检测 Xamarin.forms android 中的网络调用?
- python - Django 框架 - 填充模型
- redis - 在 Redis 中查询频率统计信息?
- python - 删除一个词,除非它是另一个词的一部分
- docker - 使用 MinGW 编译的 Qt5 构建 Docker 映像在从“docker:latest”映像运行的容器中工作,但在 GitLab CI 中失败
- php - simplexml_load_string 不接受单个 XML 标记