zoukankan      html  css  js  c++  java
  • .net Core把一个list集合里面的所有字段的数值汇总

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

    在很多时候,得到一个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;
            }
  • 相关阅读:
    原生js实现基本选择器
    javascript数组
    web中关于隐藏与显示
    CSS3 box-shadow(阴影使用)
    java中文件的I/O操作
    组件RecyclerView的应用(一)
    Android客户端与Eclipse服务器端的Socket通信
    C语言关于利用sscanf实现字符串相加减
    TabLayout和ViewPager简单实现页卡的滑动
    DrawerLayout的openDrawer()和closeDrawer()方法
  • 原文地址:https://www.cnblogs.com/haixiaocan/p/11163068.html
Copyright © 2011-2022 走看看