简体   繁体   English

按 linq 排序,不同和 select 前 5 个结果

[英]Order by, distinct and select top 5 results with linq

Hi everyone I'm trying to select 5 distinct records from the db but I need to be ordered and distinct.大家好,我正在尝试 select 来自数据库的 5 条不同记录,但我需要有序且不同。 I am looking for most efficient way to do so.我正在寻找最有效的方法。 The thing is that Distinct() method messes up ordering, So I am trying to achieve it by grouping them, but it seems that grouping also messes up the ordering.问题是 Distinct() 方法打乱了排序,所以我试图通过对它们进行分组来实现它,但似乎分组也打乱了排序。 Maybe someone would have a good solution?也许有人会有一个好的解决方案?

That's my current try.这是我目前的尝试。

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;


        }
    }

Does something like this work?这样的事情有用吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM