一、模擬初始化集合數據
List<Student> students = new List<Student>()
{
new Student(){ Age=18,Name="jom"}, new Student(){ Age=28,Name="bom"}, new Student(){ Age=18,Name="day"}, new Student(){ Age=38,Name="jim"}, new Student(){ Age=38,Name="lxsh"}, };
二、將集合數據按照年齡分組並取出分組大於1的
var sameAges = students.GroupBy(g => g.Age).Where(s => s.Count() > 1).ToList();
三、將年齡相同的打印出來
sameAges.ForEach(s => {
Console.WriteLine($"*******年齡為{s.Key}一共{ s.Count()}人*******"); s.ForEach(o => Console.WriteLine(o.Name)); });
四、運行效果