选择linq最新的组中的数据

时间:2013-12-09 10:00:06

标签: c# linq

如果我有这样的数据:

UserId / Department / AddedOn
1 / IT / 2012.10.1
2 / IT / 2012.11.1
3 / Sale / 2012.10.2
4 / Sale / 2012.9.1

我想得到他们部门最新的最新用户

var query  = _dbConetxt.DepartmentUsers.GroupBy(x=>x.Department)
.Select(x=>new{
x.Key, // this is Department
UserId = null // <--- this is my question, how to get this UserId by lastest AddedOn
});

1 个答案:

答案 0 :(得分:2)

只需按日期添加降序对每个组进行排序,然后选择第一个用户:

var query  = dbContext.Users
                 .GroupBy(u => u.Department)
                 .Select(g => g.OrderByDescending(u => u.AddedOn).First());

这将返回每个部门最近添加的用户(您甚至不需要创建匿名类型)。