Nexiv
Nexiv

Reputation: 49

Linq Grouping Order By Date then Time

Good Evening,

I've managed to get my Linq query almost correct. There is just one more issue I'm struggling to resolve.

My query is

var o =
  (from c in x
   group c by x.Date.Date into cc
   select new 
   { 
      Group = cc.Key.Date, 
      Items = cc.ToList(),
      ItemCount = cc.Count() 
   }).OrderByDescending(p => p.Group);

Now this query works fine. It groups within a ListView by the date. x.Date is a DateTime field in my SQL Database. Therefore I'm selecting x.Date.Date to Group by the actual Date of the DateTime field, as if it was just x.Date it would Group by the date and time.

My question is, how do I group by time so the newest time is at the top of the group?

Many thanks

Upvotes: 3

Views: 2088

Answers (3)

MaxPRafferty
MaxPRafferty

Reputation: 4977

Use the linq "ThenBy()" method:

var o = (from c in x group c by x.Date.Date into cc select new 
  { 
    Group = cc.Key.Date, 
    Items = cc.OrderByDescending(y=>y.Date).ToList(), 
    ItemCount = cc.Count() 
  })
  .OrderByDescending(p => p.Group)      

Upvotes: 4

Bob Vale
Bob Vale

Reputation: 18474

var o =
  (from c in x
   group c by c.Date.Date into cc
   select new 
   { 
      Group = cc.Key.Date, 
      Items = cc.OrderByDescending(a=>a.Date.Time).ToList(),
      ItemCount = cc.Count() 
   }).OrderByDescending(p => p.Group);

Upvotes: 1

Buu
Buu

Reputation: 50335

Change Items = cc.ToList() to Items = cc.OrderBy(c => c.[field_you_want_to_sort_by]).ToList()

Upvotes: 2

Related Questions