Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort within a group in Entity Framework

I am using Entity Framework 6 and want to group some data with GROUP BY. I have to sort both the groups AND the data within a group. To make things as easy as possible I wrote a minimalistic example.

Let's assume we have some articles with a Created-Field (only Date). I want to group all articles that are written on one day. And I want to group the articles itself within a group by the Created-Field.

This was my approach:

var articleGroups = DBContext.Articles
    .OrderByDescending(x => x.Created)
    .GroupBy(x => x.Created)
    .OrderByDescending(x => x.Key)
;

The groups are ordered perfectly but the ordering of the group itself is completely ignored. What am I doing wrong?

like image 300
Alexander Schmidt Avatar asked Nov 06 '15 10:11

Alexander Schmidt


2 Answers

Thanks for the responses. It seems that I just found a solution to my own problem ;)

var articleGroups = DBContext.Articles
    .GroupBy(x => x.Created)
    .Select(x => new {
        Created = x.Key,
        Items = x.OrderByDescending(y => y.Created)
    })
    .OrderByDescending(x => x.Created)
;
like image 91
Alexander Schmidt Avatar answered Nov 01 '22 13:11

Alexander Schmidt


Try this:

var articleGroups = DBContext.Articles
    .GroupBy(x => x.Created, 
             (x, g) => new{Key=x, Group = g.OrderByDescending(c=>c.Created)})
    .OrderByDescending(x => x.Key);

This example use signature of GroupBy with element and result selector to leverage on objects in group.

like image 43
Kirill Bestemyanov Avatar answered Nov 01 '22 11:11

Kirill Bestemyanov