2

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?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
JackLupino
  • 63
  • 1
  • 5

2 Answers2

1

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) });
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30
0

If you want to use a lambda expression inside another one, then here is a link ti an answer I gave to another question, where you can do it. Pass expression parameter as argument to another expression

Community
  • 1
  • 1
MBoros
  • 1,090
  • 7
  • 19