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();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值