【问题标题】:Linq Expression in Case StatementCase 语句中的 Linq 表达式
【发布时间】:2015-08-28 09:47:03
【问题描述】:

我在我的选择中使用带有表达式树和 case 语句的 LINQ。我这样做是因为 Where Condition 是动态构建的,并且在我的 Result 中,我需要知道 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) });

知道怎么做吗?

【问题讨论】:

    标签: c# linq case expression-trees


    【解决方案1】:

    如果查询数据库,可以先提交查询,然后应用编译后的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) });
    

    【讨论】:

      【解决方案2】:

      如果您想在另一个表达式中使用 lambda 表达式,那么这里有一个链接,我给出了另一个问题的答案,您可以在其中执行此操作。 Pass expression parameter as argument to another expression

      【讨论】:

        猜你喜欢
        • 2011-03-28
        • 1970-01-01
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多