Search code examples
c#linqienumerableexpression-treesiqueryable

C# Make one expression tree into two (or two new expression trees with divided logic)


This question was already answer in the opposite way here, but reverting the logic is easier said than done.

So let me give you a very concrete example:

I have this :

  • e => e.Description == "sum" && e.Summary == "asd"

i want to split this to:

  • e => e.Description == "sum"
  • e => e.Summary == "asd"

In practical, linq way, i want to archieve this:

        var t = list
            .Where(e => e.Description == "sum" && e.Summary == "asd")
            .Take(2)
            .ToList();

// To

        var x = list
            .Where(e => e.Description == "sum")
            .Where(l => l.Summary == "asd")
            .Take(2)
            .ToList();

I know that the result is the same, i want to make them run in separate linq expressions.

Thank you.


Solution

  • Well without additional type checking:

    var lambda = // assign first
    
    var binary = (BinaryExpression)lambda.Body;
    
    var lambdaLeft = Expression.Lambda<Func<Some, bool>>(binary.Left, lambda.Parameters[0]);
    
    var lambdaRight = Expression.Lambda<Func<Some, bool>>(binary.Right, lambda.Parameters[0]);