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不同,不為一組

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM