Search code examples
c#entity-frameworklinq.net-6.0

How to craft a linq query with a multi-column "Group By"


How might I convert the following into a LINQ expression? I have an active EntityFramework context for the database model, I just get lost looking at the LINQ "group" docs.

SELECT TOP 1
    ContributorId,
    MAX(Version) 'Version',
    CASE
        WHEN CONVERT(varchar, max(CreateTS), 23) >= CONVERT(varchar, max(UpdateTS), 23) 
            THEN CONVERT(varchar, max(CreateTS), 23)
        ELSE CONVERT(varchar, max(UpdateTS), 23) 
    END 'Date'
FROM [MyDB].[dbo].[Contributions]
WHERE ContributorId = '08db4b393b1f'
GROUP BY 
    ContributorId,
    Version,
    CONVERT(varchar, CreateTS, 23),
    CONVERT(varchar, UpdateTS, 23)
ORDER BY 
    Version DESC

Solution

  • var result = dbContext.Contributions
        .Where(c => c.ContributorId == "08db4b393b1f")
        .GroupBy(c => new { c.ContributorId, c.Version, Date = (c.CreateTS >= c.UpdateTS ? c.CreateTS.Date : c.UpdateTS.Date) })
        .Select(g => new {
            g.Key.ContributorId,
            Version = g.Max(c => c.Version),
            Date = g.Max(c => (c.CreateTS >= c.UpdateTS ? c.CreateTS.Date : c.UpdateTS.Date))
        })
        .OrderByDescending(r => r.Version)
        .Take(1)
        .SingleOrDefault();
    

    I think this should be it.