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); }
這個例子中就充分利用了匿名類型。
張志敏所有文章遵循創作共用版權協議,要求署名、非商業 、保持一致。在滿足創作共用版權協議的基礎上可以轉載,但請以超鏈接形式注明出處。
本博客已經遷移到 GitHub , 圍觀地址: https://beginor.github.io/
浙公網安備 33010602011771號