C#-Group By 的使用

2023-10-19 18:47:10 浏览数 (1)

group by 是linq中的分组功能,能通过给定的字段对数据集进行分组,得到分组后的结果。

基本用法

使用扩展函数GroupBy对数据集合通过给定的字段进行分组,新建一个基于.net6的控制台项目,在program.cs中写如下代码,通过班级将学生进行分组展示(顶级语句 ,从 C# 9 开始,无需在控制台应用程序项目中显式包含 Main 方法。 相反,可以使用顶级语句功能最大程度地减少必须编写的代码。 在这种情况下,编译器将为应用程序生成类和 Main 方法入口点。):

代码语言:javascript复制
// See https://aka.ms/new-console-template for more information

List<Student> students = new List<Student>() {
    new Student(){Name="1",Classroom="a"},
    new Student(){Name="2",Classroom="a"},
    new Student(){Name="3",Classroom="b"},
    new Student(){Name="4",Classroom="b"}
};

var groupStudents=students.GroupBy(student=>student.Classroom);

foreach(var groupStudent in groupStudents)
{
    Console.WriteLine(groupStudent.Key);
    foreach(var student in groupStudent)
    {
        Console.WriteLine($"{student.Name},{student.Classroom}");
    }
}



public class Student
{
    public string Name { get; set; }
    public string Classroom { get; set; }

}

分组求和

统计某同学的总分,参考代码:

代码语言:javascript复制
// See https://aka.ms/new-console-template for more information


List<Student> students = new List<Student>() {
    new Student(){Name="小明",Classroom="a班",Subjects="数学",Score=100},
    new Student(){Name="小彭",Classroom="a班",Subjects="数学",Score=100},
    new Student(){Name="小明",Classroom="a班",Subjects="语文",Score=90},
    new Student(){Name="小黄",Classroom="b班",Subjects="语文",Score=90}
};

var groupStudents = from student in students
                    group student by new { student.Name, student.Classroom }
                    into res
                    select new Student
                    {
                        Name = res.First().Name,
                        Classroom = res.First().Classroom,
                        Subjects = "已考科目总分",
                        Score = res.Sum(x => x.Score),
                    };


foreach (var groupStudent in groupStudents)
{
    Console.WriteLine($"{groupStudent.Name},{groupStudent.Classroom},{groupStudent.Subjects},{groupStudent.Score}");
}



public class Student
{
    /// <summary>
    /// 姓名
    /// </summary>
    public string Name { get; set; }
    /// <summary>
    /// 班级
    /// </summary>
    public string Classroom { get; set; }
    /// <summary>
    /// 科目
    /// </summary>
    public string Subjects { get; set; }
    /// <summary>
    /// 分数
    /// </summary>
    public float Score { get; set; }

}

0 人点赞