.net Core把一个list集合里面的所有字段的数值汇总
生活随笔
收集整理的這篇文章主要介紹了
.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;}?
轉載于:https://www.cnblogs.com/haixiaocan/p/11163068.html
總結
以上是生活随笔為你收集整理的.net Core把一个list集合里面的所有字段的数值汇总的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 就这么狐闹剧情介绍
- 下一篇: 重返帝国信物怎么获得?