如何使用Linq从对象列表中按月份分组获取最大与最小计数
解决方案
步骤说明
- 按Month分组并统计数量:利用Linq的
GroupBy方法按Month字段分组,通过Count()统计每组元素数量,最终转为字典存储月份与对应计数的映射关系。 - 获取最大/最小计数及对应月份:从字典的
Values集合中调用Max()和Min()得到最大、最小计数,再反向查找对应的月份。
完整代码实现
using System; using System.Collections.Generic; using System.Linq; public class Test { public string Month { get; set; } public string ID { get; set; } public string SubMonth { get; set; } } class Program { static void Main() { List<Test> test = new List<Test>(); test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep2" }); test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep3" }); test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep4" }); test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep5" }); test.Add(new Test { Month = "Sep", ID = "1", SubMonth = "Sep6" }); test.Add(new Test { Month = "Jun", ID = "3", SubMonth = "Jun2" }); test.Add(new Test { Month = "Jul", ID = "4", SubMonth = "Jul2" }); test.Add(new Test { Month = "Jul", ID = "4", SubMonth = "Jul3" }); test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan2" }); test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan3" }); test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan4" }); test.Add(new Test { Month = "Jan", ID = "5", SubMonth = "Jan5" }); // 分组统计每个月份的元素数量 var monthCountMap = test.GroupBy(t => t.Month) .ToDictionary(group => group.Key, group => group.Count()); // 获取最大计数及对应月份 int maxCount = monthCountMap.Values.Max(); string maxMonth = monthCountMap.First(kv => kv.Value == maxCount).Key; // 获取最小计数及对应月份 int minCount = monthCountMap.Values.Min(); string minMonth = monthCountMap.First(kv => kv.Value == minCount).Key; // 输出结果 Console.WriteLine($"最大计数:{maxMonth}月,共{maxCount}个元素"); Console.WriteLine($"最小计数:{minMonth}月,共{minCount}个元素"); } }
输出结果
最大计数:Sep月,共5个元素 最小计数:Jun月,共1个元素
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

