开发者

Linq To SQL: Distinct with First or Default

开发者 https://www.devze.com 2022-12-21 21:37 出处:网络
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 fi开发者_JS百

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 fi开发者_JS百科ne. 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.


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());
0

精彩评论

暂无评论...
验证码 换一张
取 消