tags:

views:

39

answers:

1

I have a table of Departments that is related to an Employees table. What I want is a list that contains one Employee for every Department. It doesn't matter which employee, so TOP 1, is fine. But each Department should only be represented by one employee in the list.

EMPLOYEES >----------DEPARTMENT
Id                   Id
LastName             DepartmentName
DepartmentId

How do I write that LINQ query? I'm missing something here, becuase I didn't think this would be hard to figure out.

+1  A: 

I'd use GroupBy and First. No need for any special joins on the Department table at all.

Context.Employees.GroupBy(x => x.DepartmentId).Select(x => x.First());
David Morton
i would correct to FirstOrDefault, otherwise you get expection if there none. or not? in case of groupby?
Andrey
@Andrey There will never "not be" an item in a group. The groups are defined by the collection of employees, so there is guaranteed to _always_ be at least one employee in any group defined in the GroupBy clause.
David Morton
Boy, was I making that much more difficult than it really was! Thanks David!
jlembke