zoukankan      html  css  js  c++  java
  • Linq 中按照多个值进行分组(GroupBy)

    /// <summary>要查询的对象</summary>
    class Employee {
       public int ID { get;set; }
       public string FName { get; set; }
       public int Age { get; set; }
       public char Sex { get; set; }
    }

    如果对这个类的Age和Sex的连个字段进行分组,方法如下:

    // 先造一些数据
    List<Employee> empList = new List<Employee>();
    empList.Add(new Employee() {
       ID = 1, FName = "John", Age = 23, Sex = 'M'
    });
    empList.Add(new Employee() {
       ID = 2, FName = "Mary", Age = 25, Sex = 'F'
    });
    
    empList.Add(new Employee() {
       ID = 3, FName = "Amber", Age = 23, Sex = 'M'
    });
    empList.Add(new Employee() {
       ID = 4, FName = "Kathy", Age = 25, Sex = 'M'
    });
    empList.Add(new Employee() {
       ID = 5, FName = "Lena", Age = 27, Sex = 'F'
    });
    
    empList.Add(new Employee() {
       ID = 6, FName = "Bill", Age = 28, Sex = 'M'
    });
    
    empList.Add(new Employee() {
       ID = 7, FName = "Celina", Age = 27, Sex = 'F'
    });
    empList.Add(new Employee() {
       ID = 8, FName = "John", Age = 28, Sex = 'M'
    });

    接下来的做法是:

    // 实现多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);
    }

    这个例子中就充分利用了匿名类型。

    本文 转载自:http://www.cnblogs.com/beginor/archive/2009/04/24/1442939.html

  • 相关阅读:
    Linux下编辑、编译、调试命令总结——gcc和gdb描述
    scanf函数读取缓冲区数据的问题
    Windows下设置Ubuntu引导项
    前端术语汇总笔记(会保持更新)
    实现动态加载一个 JavaScript 资源
    提取一个字符串中的数字,并将其转为数组
    CSS3图片倒影技术
    js函数聚合
    js继承函数封装
    联动菜单实现思路
  • 原文地址:https://www.cnblogs.com/ItDotNet/p/5318184.html
Copyright © 2011-2022 走看看