gpt4 book ai didi

c# - Case 语句中的 Linq 表达式

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:06 24 4
gpt4 key购买 nike

我在我的 Select 中使用带有表达式树和 case 语句的 LINQ。我这样做是因为 Where 条件是动态构建的,在我的结果中,我需要知道 where 的哪一部分是真的。

这很好用:

ParameterExpression peTbl = Expression.Parameter(typeof(MyTbl), "mytbl");

Expression left = Expression.Property(peTbl, "Col1");
Expression right = Expression.Constant((ulong)3344, typeof(ulong));
Expression e1 = Expression.Equal(left, right);

left = Expression.Property(peTbl, "Col2");
right = Expression.Constant((ulong)27, typeof(ulong));
Expression e2 = Expression.Equal(left, right);

Expression predicateBody = Expression.Or(e1, e2);

Expression<Func<MyTbl, bool>> whereCondition = Expression.Lambda<Func<MyTbl, bool>>(predicateBody, new ParameterExpression[] { peTbl });

var query = myTbl.Where(whereCondition)
.Select(s => new { mytbl = s, mycase = (s.Col1 == 3344 ? 1 : 0) });

但是现在,我想在我的 case 语句中使用表达式 e1。

像这样:

var query = myTbl.Where(whereCondition)
.Select(s => new { mytbl = s, mycase = (e1 == true ? 1 : 0) });

知道怎么做吗?

最佳答案

如果你查询一个数据库,你可以先提交查询然后应用编译的e1:

  var e1Compiled = Expression.Lambda<Func<MyTbl,bool>>(e1, peTbl).Compile();
var query = myTbl
.Where(whereCondition).ToList()
.Select(s => new { mytbl = s, mycase = (e1Compiled(s) ? 1 : 0) });

如果没有数据库,直接使用编译好的e1:

  var query = myTbl
.Where(whereCondition)
.Select(s => new { mytbl = s, mycase = (e1Compiled(s) ? 1 : 0) });

关于c# - Case 语句中的 Linq 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32268090/

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