C# List (DataTable, ArrayList, Dictionary) collection Linq to Entity Lamda grouping and summing and averaging

public class SuperHourModel
    {
        /// <summary>
        /// 站点编码
        /// </summary>
        public string SStation{ get; set; }
        
        /// <summary>
        /// 小时值
        /// </summary>
        public decimal? SValue{ get; set; }
        
        /// 参数名称
        /// </summary>
        public string  Name { get; set; }
        /// <summary>
     
    }

Requirements, group the SuperHourModel collection according to the Name attribute, and calculate the average value of Svalue. And sort the parameter names and values ​​of the first ten items in descending order.

 List<SuperHourModel> list = dataList.Where(P => P.SStation == station).GroupBy(g => new { g.Name }).Select(group => new SuperHourModel
                    {
                        Name = group.Key.Name,
                        SValue =Math.Round(Convert.ToDecimal(group.Average(q => q.SValue)),3)
                    }).OrderByDescending(p => p.SValue).Take(10).ToList(); 

ps: In the end, an error was reported by using the Math.Round(group.Average(q => q.SValue),3) function to retain 3 decimal places. It cannot be converted from "decimal?" to "decimal

 The solution is Math.Round(Convert.ToDecimal(group.Average(q => q.SValue)),3).

The final rendering

 

Code for more linq extensions:

//单字段分组并求和:
var list = data.GroupBy(g => g.GoodsId).Select(e => new { GoodsId = e.Key, Qty = e.Sum(q => q.Qty) });

//多字段分组求和:
var list = data.GroupBy(g => new { g.StorageId,g.GoodsId }).Select(e => new { GoodsId = e.Key, Qty = e.Sum(q => q.Qty) });

//多字段 分组求均值 
List<SuperHourModel> list = dataList.Where(P => P.SStation == station).GroupBy(g => new { g.Name }).Select(group => new SuperHourModel
 {
     Name = group.Key.Name,
     SValue =group.Average(q => q.SValue)
}).OrderByDescending(p => p.SValue).Take(10).ToList(); 

Guess you like

Origin blog.csdn.net/qq_26695613/article/details/130228060