将Linq Group转换为用户定义的类型

时间:2011-12-28 11:35:24

标签: c# entity-framework linq linq-group

我正在研究ac #project并编写LINQ查询,在这个查询中我需要创建一个组,但我知道我想要使用该组类型,但是组的类型给我带来了一些麻烦,因为我无法将其转换为我想要的类型。

我的查询

from emp in employees
join dept in departments
on emp.EmpID equals dept.EmpID
group dept by dept.EmpID into groupSet
select new mycustomType
{
    Department = groupSet
});

1 个答案:

答案 0 :(得分:0)

您尚未显示任何类型的签名。我们只能猜测你想要的类型看起来如何。下次提出问题时,请确保提供SSCCE

无论如何,根据你的例子,这个自定义类型应该是这样的:

public class MyCustomType
{
    public IGrouping<int, Department> Department { get; set; }
}

其中Departmentdepartments集合中的元素类型,它假定EmpID的类型为整数。

示例:

IEnumerable<Employee> employees = ...
IEnumerable<Department> departments = ...

IEnumerable<MyCustomType> result = 
    from emp in employees
    join dept in departments
    on emp.EmpID equals dept.EmpID
    group dept by dept.EmpID into groupSet
    select new MyCustomType
    {
        Department = groupSet
    };