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; }
    }
    // 先造一些数据
    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);
    }

    断点调试的结果是:

    输出结果是

    下面等同的linq的写法如下:

                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);
                }

    总结:多key分组是一种一维的分组,不是组内分组,多个key完全相同时,即为一组,只要有一个key不同,不为一组

  • 相关阅读:
    webapi支持session
    webapi返回数据同时支持xml与json
    webapi权限控制
    Asp.net 将js文件打包进dll 方法
    All Media to FLV asp.net在线视频自动转换并截图调试成功!
    未能从程序集“System.ServiceModel
    [javascript]浮动广告
    [python]multi thread tcp connect port scanner
    [vc]让你Y的用YY
    [python]扫描网站后台脚本
  • 原文地址:https://www.cnblogs.com/tianyang1027/p/13931811.html
Copyright © 2011-2022 走看看