【C#】list集合對多個字段group by、order by排序并新增字段
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
public class Employee
{
public int ID {get;set;}
public string FName {get;set;}
public int Age {get;set;}
public char Sex {get;set;}
}
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'}
};
// 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
//返回結(jié)果同上
var query=from el in empList group el by new {el.Age,el.Sex} into g elect new {g.Key, Count=g.Count()};
foreach (var employee in query /* Or QueryWithLamda */ )
Console.WriteLine(employee.Count);
}
該文章在 2021/3/9 18:43:00 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |