简体   繁体   中英

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

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)      

Items = cc.ToList()更改为Items = cc.OrderBy(c => c.[field_you_want_to_sort_by]).ToList()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM