Alexander Schmidt
Alexander Schmidt

Reputation: 183

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?

Upvotes: 5

Views: 6032

Answers (3)

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

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.

Upvotes: 2

StepUp
StepUp

Reputation: 38094

If I understood correctly:

List<Articles> list = new List<Articles>() 
{
   new Articles(){DateCreated=new DateTime(2015, 1, 18), Smth="aa1"},
   new Articles(){DateCreated=new DateTime(2015, 1, 18), Smth="aa2"},
   new Articles(){DateCreated=new DateTime(2014, 1, 18), Smth="aa3"},
   new Articles(){DateCreated=new DateTime(2014, 1, 18), Smth="aa4"},
   new Articles(){DateCreated=new DateTime(2016, 1, 18), Smth="aa5"},
   new Articles(){DateCreated=new DateTime(2016, 1, 18), Smth="aa6"},
   new Articles(){DateCreated=new DateTime(2012, 1, 18), Smth="aa7"},
   new Articles(){DateCreated=new DateTime(2012, 1, 18), Smth="aa8"},
   new Articles(){DateCreated=new DateTime(2018, 1, 18), Smth="aa9"},
   new Articles(){DateCreated=new DateTime(2018, 1, 18), Smth="aa10"},
};
var yourQuery = (from p in list group p.DateCreated by p.DateCreated into g select new { ByDate = g.Key, GroupedColl=g.ToList() }).OrderBy(x=>x.ByDate);

Article Class:

class Articles 
{
    public DateTime DateCreated { get; set; }
    public string Smth { get; set; }
}

Where ByDate and GroupedColl are your data fields.

Upvotes: 0

Alexander Schmidt
Alexander Schmidt

Reputation: 183

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

Upvotes: 4

Related Questions