按顺序排列,用linq选择前5个结果。

问题描述 投票:0回答:2

嗨,大家好,我想从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;


        }
    }
c# database performance linq service
2个回答
1
投票

这样的东西能用吗?

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();
© www.soinside.com 2019 - 2024. All rights reserved.