Linq Lambda 中group by多列后count数量的写法
直接上代码:
List<Student> ss = new List<Student>(); Student ss1 = new Student() { Id = 1, Age = 1, Name = "11" }; Student ss2 = new Student() { Id = 1, Age = 1, Name = "11" }; Student ss3 = new Student() { Id = 2, Age = 2, Name = "22" }; Student ss4 = new Student() { Id = 2, Age = 2, Name = "22" }; Student ss5 = new Student() { Id = 2, Age = 2, Name = "22" }; Student ss6 = new Student() { Id = 3, Age = 3, Name = "33" }; ss.Add(ss1); ss.Add(ss2); ss.Add(ss3); ss.Add(ss4); ss.Add(ss5); ss.Add(ss6);
// 注意select中的Count()方法必须定义成员名称,否则会报无效的匿名成员声明。 var aa = ss.GroupBy(m => new { m.Id, m.Age }).Select(group => new {group.Key.Id,group.Key.Age,count = group.Count()}).ToList(); foreach (var item in aa) { Console.WriteLine(item.Id + "||" + item.Age + "||" + item.count); } Console.ReadKey(); //结果 1 || 1 || 2 2 || 2 || 3 3 || 3 || 1