Linq 中按照多个值进行分组(GroupBy)

Posted 吴晓阳

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linq 中按照多个值进行分组(GroupBy)相关的知识,希望对你有一定的参考价值。

Linq 中按照多个值进行分组(GroupBy)
.GroupBy(x => new { x.Age, x.Sex })
group emp by new { emp.Age, emp.Sex } into g


// 实现多key分组的扩展函数版本
var sums = empList
         .GroupBy(x => new { x.Age, x.Sex })
         .Select(group => new {
            Peo = group.Key, Count = group.Count()
         });
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);
}

// 实现多key分组的lambda版本
var sums2 = from emp in empList
            group emp by new { emp.Age, emp.Sex } into g
            select new { Peo = g.Key, Count = g.Count() };
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);
}

 

以上是关于Linq 中按照多个值进行分组(GroupBy)的主要内容,如果未能解决你的问题,请参考以下文章