Stef Heyenrath
Stef Heyenrath

Reputation: 9830

A better way to build a custom SUM function which takes a list of Expressions

I've defined the following method:

public static Expression Sum(IList<Expression> expressions)
{
    Expression result = expressions[0];
    foreach (var expression in expressions.Skip(1))
    {
        result = Expression.Add(result, expression);
    }

    return result;
}

Which can be used as:

var number1 = Expression.Constant(42.0);
var number2 = Expression.Constant(10.0);

var resultExpression = Sum(new { number1, number2 });
var value = Expression.Lambda(resultExpression).Compile().DynamicInvoke();

However when adding a large number of expressions, I think the performance is not ok.

So I was wondering if a method can be created which used Enumerable.Sum or Queryable.Sum to do the work.

Upvotes: 0

Views: 382

Answers (1)

aperezfals
aperezfals

Reputation: 1389

I think you are redifining the Aggregate method, that uses a previous Add expression and current expression of your list of expression. Change your code to this:

return expressions.Aggregate((previousExpr, currentExpr) => Expression.Add(previousExpr, currentExpr));

I'm not sure this is faster, but is cleaner. previousExpr contains the exression result to sum

Upvotes: 1

Related Questions