How to merge two C# Lambda Expressions without an invoke?

前端 未结 2 1222
慢半拍i
慢半拍i 2020-12-14 21:29

I\'d like to merge the following Expressions:

// example class
class Order
{
    List Lines       
}
class OrderLine { }

Expression

        
2条回答
  •  长情又很酷
    2020-12-14 21:45

    This extension works:

    public static class Utility
        {
            public static Expression Compose(this Expression first, Expression second, Func merge)
            {
                // build parameter map (from parameters of second to parameters of first)
                var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
    
                // replace parameters in the second lambda expression with parameters from the first
                var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
    
                // apply composition of lambda expression bodies to parameters from the first expression 
                return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
            }
    
            public static Expression> And(this Expression> first, Expression> second)
            {
                return first.Compose(second, Expression.And);
            }
    
            public static Expression> Or(this Expression> first, Expression> second)
            {
                return first.Compose(second, Expression.Or);
            }
        }
    

    Sample using:

    Expression> filter1 = p => a.ProductId == 1;
    Expression> filter2 = p => a.Text.StartWith("test");
    Expression> filterCombined = filter1.And(filter2);
    

提交回复
热议问题