zoukankan      html  css  js  c++  java
  • C#集合中根据多个字段分组 group by linq表达式

    void Main()
    {
         var  empList =new List<Employee>
         {
            new Employee {ID = 1, FName = "John", Age = 23, Sex = 'M'},
            new Employee {ID = 2, FName = "Mary", Age = 25, Sex = 'F'},
            new Employee {ID = 3, FName = "Amber", Age = 23, Sex = 'M'},
            new Employee {ID = 4, FName = "Kathy", Age = 25, Sex = 'F'},
            new Employee {ID = 5, FName = "Lena", Age = 27, Sex = 'F'},
            new Employee {ID = 6, FName = "Bill", Age = 28, Sex = 'M'},
            new Employee {ID = 7, FName = "Celina", Age = 27, Sex = 'F'},
            new Employee {ID = 8, FName = "John", Age = 28, Sex = 'M'}
         };
           
      //这里是根据Age,Sex进行分组
    // query with lamda expression g.Key代表Age和Sex两字段,Count为新增字段 // 最终返回的集合QueryWithLamda包含字段:Age、Sex、Count var QueryWithLamda = empList.GroupBy(x => new { x.Age, x.Sex}) .Select(g=>new {g.Key, Count=g.Count()}); //query with standard expression<br> //返回结果同上 var query=from el in empList group el by new {el.Age,el.Sex} into g select new {g.Key, Count=g.Count()}; foreach (var employee in query /* Or QueryWithLamda */ ) Console.WriteLine(employee.Count); } public class Employee { public int ID {get;set;} public string FName {get;set;} public int Age {get;set;} public char Sex {get;set;} }
  • 相关阅读:
    CF 461B Appleman and Tree
    POJ 1821 Fence
    NOIP 2012 开车旅行
    CF 494B Obsessive String
    BZOJ2337 XOR和路径
    CF 24D Broken robot
    POJ 1952 BUY LOW, BUY LOWER
    SPOJ NAPTIME Naptime
    POJ 3585
    CF 453B Little Pony and Harmony Chest
  • 原文地址:https://www.cnblogs.com/loushengjie/p/11698059.html
Copyright © 2011-2022 走看看