如何获得IEnumerable< object>的linq和 [英] How to get linq sum of IEnumerable<object>

查看:98
本文介绍了如何获得IEnumerable< object>的linq和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取IEnumerable对象集合中的数字总和?我肯定知道基础类型将始终是数字,但是类型是在运行时确定的.

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();

有什么想法吗?谢谢.

推荐答案

您可以使用表达式树生成所需的add函数,然后将其折叠在输入列表上:

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.

这篇关于如何获得IEnumerable&lt; object&gt;的linq和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆