Search code examples
c#linqexpression-treeslinq-expressions

Linq - Expression.And to join N elements BinayExpression


I have a list of BinaryExpression and I need to join the elements of this list in a single "object".

IList<BinaryExpression> lstBin = new List<BinaryExpression>();

Inside my List I have this:

{(item.Field1 = 1)} //First Element
{(item.Field2 = 99)} //Second Element
//So on..

I need something like this:

(item => item.Field1 == 1 && item.Field2 == 99 && item.Field3 == 45)

I know that Linq has Expression.And, and I need to make a logic to implement this, but I couldn't. I tried to make a loop inside my list but Expression.And needs two Expression, and inside my loop I have only one. After this, I'll make a Expression.Lamba from this single "object", like this:

Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(singleExpression, parameter);

Solution

  • I think you want (with LINQ):

    var singleExpression = lstBin.Aggregate(Expression.AndAlso);
    

    If you prefer writing a loop:

    var singleExpression = lstBin.First();
    
    foreach (var expr in lstBin.Skip(1))
        singleExpression = Expression.AndAlso(singleExpression, expr);