C# GroupBy 用法

class Student
{
    public int StuId { get; set; }

    public string ClassName { get; set; }

    public string StudentName { get; set; }
}
static List<Student> studentList = new List<Student>
{
    new Student {ClassName = "软工一班", StudentName = "康巴一", StuId = 1},
    new Student {ClassName = "软工一班", StudentName = "康巴二", StuId = 2},
    new Student {ClassName = "软工一班", StudentName = "康巴三", StuId = 3},
    new Student {ClassName = "软工二班", StudentName = "康定一", StuId = 4},
    new Student {ClassName = "软工二班", StudentName = "康定二", StuId = 5},
    new Student {ClassName = "软工二班", StudentName = "康定三", StuId = 6},
};

发现只能根据一个字段进行 GroupBy,能获取到分组好的 Student 对象
根据key 值取不同分组:

static void Main(string[] args)
{
   IEnumerable<IGrouping<string,Student>> studentGroup = studentList.GroupBy(s => s.ClassName);

   foreach (IGrouping<string, Student> item in studentGroup)
   {
       Console.WriteLine(item.Key);

       //对item 在进行遍历
       foreach (Student student in item)
       {
           Console.WriteLine(student.StudentName);
       }
   }

   Console.ReadKey();
}

你可能感兴趣的:(C#)