List集合分组
Posted guozewen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了List集合分组相关的知识,希望对你有一定的参考价值。
依据班级对学生进行分组
private class Student
{
public string StuName { get; set; }
public string StuClassID { get; set; }
}
public static void ListGroup()
{
List<Student> slist = new List<Student>(){
new Student { StuName = "王小明701", StuClassID = "701班" },
new Student { StuName = "李晓红701", StuClassID = "701班" },
new Student { StuName = "红小鸡701", StuClassID = "701班" },
new Student { StuName = "李大大801", StuClassID = "801班" },
new Student { StuName = "林炫均701", StuClassID = "701班" },
new Student { StuName = "红孩儿901", StuClassID = "901班" },
new Student { StuName = "丽水市901", StuClassID = "901班" },
new Student { StuName = "徐税务801", StuClassID = "801班" },
};
//方式1
var groupres = slist.GroupBy(items => items.StuClassID);
//方式2
groupres = from s in slist
group s by s.StuClassID;
foreach (var item in groupres)
{
//groupres:IEnumerable<IGrouping<string, Student>>
//item.Key:分组的键
//item:分组后的数据源
Console.WriteLine(item.Key);
foreach (Student s in item)
{
Console.WriteLine(s.StuName);
}
}
}
测试结果:
以上是关于List集合分组的主要内容,如果未能解决你的问题,请参考以下文章