假设我有一个Employee类,GetAllEmployees()返回一个Employee实例列表:
from employee in Employee.GetAllEmployees()
group employee by new { employee.Department, employee.Gender } into egroup
select new
{
Dept = egroup.Key.Department,
Gender = egroup.Key.Gender,
Employees = egroup.OrderBy(x => x.Name)
};
根据我的理解,egroup是一个关键值对,所以使用egroup.Key是公平的,但为什么我们不需要编写像Employees = egroup.Value这样的东西?看起来egroup与egroup.Value相同?
答案 0 :(得分:1)
实际上 egroup 不是键/值对,而是IGrouping<TKey, TElement>
。
IGrouping<TKey, TElement>
表示共享相同密钥的对象集合。基本上,您可以访问Key
,因为它对所有元素都很常见,但您无法像egroup.Value
那样直接访问某些元素。
无论如何,您可以将 egroup 转换为List<T>
。在你的情况下,它将是:
from employee in Employee.GetAllEmployees()
group employee by new { employee.Department, employee.Gender } into egroup
select new
{
Dept = egroup.Key.Department,
Gender = egroup.Key.Gender,
Employees = egroup.ToList()
};
现在Employees
的类型为List<Employee>
。