LINQ: Group by month and year within a datetime field

前端 未结 5 1161
轻奢々
轻奢々 2020-12-08 00:38

I have a table with a datetime field. I want to retrieve a result set grouped by the month/year combination and the number of records that appear within that month/year. H

5条回答
  •  情书的邮戳
    2020-12-08 01:00

    var grouped = from p in posts
         group p by new { month = p.Create.Month,year= p.Create.Year } into d
         select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count() };
    

    Here's the list of DateTime functions available in LINQ. For this to work you'll also need to understand multi-column grouping

    ordered descending

    var grouped = (from p in posts 
      group p by new { month = p.Create.Month,year= p.Create.Year } into d 
      select new { dt = string.Format("{0}/{1}",d.Key.month,d.Key.year), count = d.Count()}).OrderByDescending (g => g.dt);
    

提交回复
热议问题