Mike Mike - 1 year ago 66
C# Question

How to get linq sum of IEnumerable<object>

How do I get the sum of numbers that are in an IEnumerable collection of objects? I know for sure that the underlying type will always be numeric but the type is determined at runtime.

IEnumerable<object> listValues = data.Select(i => Convert.ChangeType(property.GetValue(i, null), columnType));

After that I want to be able to do the following (the following has the error:"Cannot resolve method Sum"):

var total = listValues.Sum();

Any ideas? Thank you.

Lee Lee
Answer Source

You can use expression trees to generate the required add function, then fold over your input list:

private static Func<object, object, object> GenAddFunc(Type elementType)
    var param1Expr = Expression.Parameter(typeof(object));
    var param2Expr = Expression.Parameter(typeof(object));
    var addExpr = Expression.Add(Expression.Convert(param1Expr, elementType), Expression.Convert(param2Expr, elementType));
    return Expression.Lambda<Func<object, object, object>>(Expression.Convert(addExpr, typeof(object)), param1Expr, param2Expr).Compile();

IEnumerable<object> listValues;
Type elementType = listValues.First().GetType();
var addFunc = GenAddFunc(elementType);

object sum = listValues.Aggregate(addFunc);

note this requires the input list to be non-empty, but it has the advantage of preserving the element type in the result.