• Linq 和 Lambda 查询中按照多个值进行分组GroupBy


    创建要查询的对象:
    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分组的Linq扩展函数版本
    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);
    }
  • 相关阅读:
    unity ab包打包和加载的简单学习示例
    项目整理回顾1,关于单例使用
    关于lua闭包导致引用无法释放内存泄露
    unity lua require dofile loadfile 区别
    unity editor模式下读取文件夹资源
    unity texture 占用内存大小对比
    关于unity贴图压缩
    内聚,耦合,解耦和,依赖倒置
    lua type 获取 类型
    Unity+NGUI多分辨率适配方案
  • 原文地址:https://www.cnblogs.com/teng-0802/p/9055779.html
Copyright © 2020-2023  润新知