.net Core把一个list集合里面的所有字段的数值汇总

作者为学习记录写此随笔,在获取list集合后想汇总其中数据,因在.net core官方文档未找到相关方法,便自行编写了一个方法来汇总list集合里所有数值类型的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:此随笔仅供自己学习,如有不足还请指出

在很多时候,得到一个list集合,需要把里面的数据汇总,但我又不想写那么多循环,于是去.net core 官方文档找有没有相关方法,很可惜我没有找到,所以就自己写了一个方法,用来把list集合里面所有的数值类型都汇总起来。

/// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lists">数据集</param>
        /// <returns></returns>
        public T CollectionSummary<T>(List<T> lists) where T : class, new()
        {
            Type entityType = typeof(T);
            T generic = new T();
            var entityProperties = entityType.GetProperties();
            Dictionary<Type, Func<PropertyInfo, object>> map = new Dictionary<Type, Func<PropertyInfo, object>>
            {
                { typeof(double), property=>lists.Sum(item => (double)property.GetValue(item)) },
                { typeof(float), property=>lists.Sum(item => (float)property.GetValue(item)) },
                { typeof(decimal), property=>lists.Sum(item => (decimal)property.GetValue(item)) },
                { typeof(long), property=>lists.Sum(item => (long)property.GetValue(item)) },
                { typeof(int), property=>lists.Sum(item => (int)property.GetValue(item)) },
                { typeof(short), property=>lists.Sum(item => (short)property.GetValue(item)) },
                { typeof(byte), property=>lists.Sum(item => (byte)property.GetValue(item))},
            };
            foreach (var property in entityProperties)
            {
                if (map.ContainsKey(property.PropertyType))
                {
                    property.SetValue(generic, map[property.PropertyType](property));
                }
            }
            return generic;
        }

 

转载于:https://www.cnblogs.com/haixiaocan/p/11163068.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值