【发布时间】:2020-08-22 23:28:30
【问题描述】:
大家好,我正在尝试从数据库中选择 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;
}
}
【问题讨论】:
-
我建议尝试将排序列添加到结果中,例如
.OrderByDesc(x => x.End).Distinct().Select(x => new{x.End, dto = new RecentProjectDto{....}}).Take(5).ToList()并删除GroupBy -
你的
.OrderByDescending应该在Groupby之后 -
@Rahul group by 不包括排序列。
-
@GuruStron 是的,我按照 SQL 的执行顺序进行
-
@Sajid 好像涉及到db,所以代码转成SQL,不关心比较器。
标签: c# database performance linq service