我在表达式树中使用LINQ并在我的Select中使用了case语句。我这样做是因为Where Condition是动态构建的,而且在我的结果中,我需要知道哪里的哪部分是真的。Linq在Case语句中的表达式
这工作得很好:
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) });
但现在,我想用表达E1在我的case语句。
事情是这样的:
var query = myTbl.Where(whereCondition)
.Select(s => new { mytbl = s, mycase = (e1 == true ? 1 : 0) });
任何想法如何做到这一点?