LINQ: Group by month and year within a datetime field

前端 未结 5 1130
轻奢々
轻奢々 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:19

    This is for those who are trying to accomplish the same but using lambda expressions.

    Assuming that you already have a collection of entities and each entity has OrderDate as one of its properties.

    yourCollection
    // This will return the list with the most recent date first.
    .OrderByDescending(x => x.OrderDate)
    .GroupBy(x => new {x.OrderDate.Year, x.OrderDate.Month})
    // Bonus: You can use this on a drop down
    .Select(x => new SelectListItem
            {
               Value = string.Format("{0}|{1}", x.Key.Year, x.Key.Month),
               Text = string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count())
            })
    .ToList();
    

    If you do not need the collection of SelectListItem then just replace the select with this one:

    .Select(x => string.Format("{0}/{1} (Count: {2})", x.Key.Year, x.Key.Month, x.Count()))
    

提交回复
热议问题