1. 程式人生 > >List集合分組

List集合分組

ble ssi num win ring cal void bsp ali

依據班級對學生進行分組 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); } } }
測試結果:技術分享圖片



來自為知筆記(Wiz)

List集合分組