发布于:2023-02-21 16:21:24
二、C# Linq数据分组(推荐使用)
1.简单数字分组
//简单数字分组
int[] numbers = new int[] { 1, 5, 3, 5, 7, 8, 5, 1, 1 };
var tempList = numbers.GroupBy(q => q);
foreach (var item in tempList)
{
Console.WriteLine($"{item.Key}---总共{item.Count()}个");
}
2.对象数组分组
//对象的逻辑字段分组
List<Student> stuList = new List<Student>() {
new Student(){ Name="张三",ClassName="1班"},
new Student(){ Name="李四",ClassName="1班"},
new Student(){ Name="王五",ClassName="2班"},
new Student(){ Name="赵六",ClassName="2班"},
new Student(){ Name="憋气",ClassName="2班"},
};
var tempStuList = stuList.GroupBy(q => q.ClassName);
foreach (var item in tempStuList)
{
Console.WriteLine($"【{item.Key}】---学生数量:{item.Count()} ----学生列表:{stuList.Where(q => q.ClassName == item.Key).ToJsonString()}");
}
3.组合数据分组
//组合分组,new一个匿名对象即可
query.GroupBy(q => new { q.Year, q.Month })
.Select(q => new
{
Year = q.Key.Year,
Month = q.Key.Month,
BuildAmount = q.Sum(i => i.BuildAmount),
RecAmount = q.Sum(i => i.RecAmount),
Amount = q.Sum(i => i.Amount),
RealAmount = q.Sum(i => i.RealAmount)
});
https://blog.csdn.net/u011127019/article/details/124431225
阅读 293+
10