欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#集合中根据多个字段分组 group by linq表达式

程序员文章站 2024-02-05 20:01:04
void Main() { var empList =new List { new Employee {ID = 1, FName = "John", Age = 23, Sex = 'M'}, new Employee {ID = 2, FName = "Mary", Age ... ......

 

 

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;} }