Search code examples
c#linqcaseexpression-trees

Linq Expression in Case Statement


I'm using LINQ with Expression trees and a case Statement in my Select. I'm doing this because the Where Condition is build dynamically and in my Result, I need to know, which part of the where was true.

This works fine:

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) });

But now, I want to use the Expression e1 in my case Statement.

Something like this:

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

Any idea how to do this?


Solution

  • If you query against a database, you can commit the query first and then apply the compiled 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) });
    

    if there is no database, just use the compiled e1:

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