LINQ:GroupBy
一、数据准备
public class Student { public int ID { get; set; } public string Name { get; set; } public string Gender { get; set; } public string Branch { get; set; } public int Age { get; set; } public static List<Student> GetAllStudents() { return new List<Student>() { new Student { ID = 1001, Name = "玲玲", Gender = "Female", Branch = "CSE", Age = 20 }, new Student { ID = 1002, Name = "张三", Gender = "Male", Branch = "ETC", Age = 21 }, new Student { ID = 1003, Name = "李四", Gender = "Male", Branch = "CSE", Age = 21 }, new Student { ID = 1004, Name = "王五", Gender = "Male", Branch = "CSE", Age = 20 }, new Student { ID = 1005, Name = "珊珊", Gender = "Female", Branch = "ETC", Age = 20 }, new Student { ID = 1006, Name = "涵涵", Gender = "Female", Branch = "CSE", Age = 21 }, new Student { ID = 1007, Name = "钱六", Gender = "Male", Branch = "CSE", Age = 22 }, new Student { ID = 1008, Name = "婷婷", Gender = "Female", Branch = "CSE", Age = 20 }, new Student { ID = 1009, Name = "兰兰", Gender = "Female", Branch = "ETC", Age = 22 }, new Student { ID = 1010, Name = "黄九", Gender = "Male", Branch = "ETC", Age = 21 } }; } }
二、GroupBy
法一Query Syntax
//Using Query Syntax Console.WriteLine("方式一:"); var GroupByQs = from std in Student.GetAllStudents() group std by std.Branch; foreach (var group in GroupByQs) { Console.WriteLine(group.Key + " : " + group.Count()); //Iterate through each student of a group foreach (var student in group) { Console.WriteLine(" Name :" + student.Name + ", Age: " + student.Age + ", Gender :" + student.Gender); } }
法二Method Syntax
Console.WriteLine("方式二:"); var GroupByMS = Student.GetAllStudents().GroupBy(s => s.Branch); //It will iterate through each groups foreach (var group in GroupByMS) { Console.WriteLine(group.Key + " : " + group.Count()); //Iterate through each student of a group foreach (var student in group) { Console.WriteLine(" Name :" + student.Name + ", Age: " + student.Age + ", Gender :" + student.Gender); } }
三、测试结果
四、参考网址
https://dotnettutorials.net/lesson/groupby-in-linq/
个人代码见....CSharpBasic\LINQTutorial..
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/keeplearningandsharing/p/16628191.html