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?
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)
;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With