嗨,大家好,我想从db中选择5条不同的记录,但我需要有序的和不同的。我正在寻找最有效的方法来做到这一点。问题是Distinct()方法会扰乱排序,所以我试图通过分组来实现,但似乎分组也会扰乱排序。也许有人会有好的解决办法?
这是我目前的尝试。
public async Task<List<RecentProjectDto>> GetMostRecentProjects(int userId, int companyId)
{
using (var db = _dbFactory.Create())
{
var recentProjects = await db.ScheduleLogs
.OfType<WorkLog>()
.Where(x => x.UserId == userId)
.Where(x => x.User.CompanyId == companyId)
.OrderByDescending(x => x.End)
.GroupBy(x => new { x.ProjectId, x.Project.Name, x.Project.Key, x.Project.Colour })
.Select(x => new RecentProjectDto
{
ProjectId = x.ProjectId,
ProjectName = x.Project.Name,
ProjectKey = x.Project.Key,
Colour = x.Project.Colour
})
.Take(5)
.ToListAsync();
return recentProjects;
}
}
这样的东西能用吗?
var recentProjects = await db.ScheduleLogs
.OfType<WorkLog>()
.Where(x => x.UserId == userId)
.Where(x => x.User.CompanyId == companyId)
.GroupBy(x => new { x.ProjectId, x.Project.Name, x.Project.Key, x.Project.Colour })
.OrderByDescending(x => x.Max(a=>a.OrderDate))
.Select(x => new RecentProjectDto
{
ProjectId = x.Key.ProjectId,
ProjectName = x.Key.Name,
ProjectKey = x.Key.Key,
Colour = x.Key.Colour
})
.Take(5)
.ToListAsync();