scr1pting
scr1pting

Reputation: 13

Linq group by count and order by last update of the group

I need to display the groupby count according to the descending order of count number followed by order of the last update row (CreatedDateTime desc). How can this be done using LINQ?

TableA.GroupBy(c => c.UserID).Select(
                    g => new { UserID = g.Key, Count = g.Count() }
                ).OrderByDescending(c => c.Count)

Here's an example of the intended ordering.

Table A
TableAID  UserID  TableBID CreatedDateTime
1         1       1        ..
2         1       1        ..
3         2       2        ..
4         2       2        ..
......

Upvotes: 1

Views: 70

Answers (1)

xanatos
xanatos

Reputation: 111890

Like this (I hope) :-)

TableA.GroupBy(c => c.UserID)
       .Select(g => new { UserID = g.Key, Count = g.Count(), g.Max(h => h.CreatedDateTime) })
       .OrderByDescending(c => c.Count)
       .ThenByDescending(c => c.CreatedDateTime)

Note that I selected the Max(CreatedDateTime). I could have used the Min(CreatedDateTime), but the result would have been different.

Upvotes: 1

Related Questions