Karlos
Karlos

Reputation: 37

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. 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. 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;


        }
    }

Upvotes: 0

Views: 782

Answers (1)

sgmoore
sgmoore

Reputation: 16077

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

Upvotes: 1

Related Questions