-2

My code here:

var query = context.Article.GroupBy(x=>x.CreateDate.Value.Month)

is not working

For example

January 2017
February 2017
March 2017
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
i.OKTURK
  • 1
  • 3
  • var query = context.Article.GroupBy(x=> new {Month = x.CreateDate.Value.Month}) check this answer https://stackoverflow.com/a/9886447/1882537 – ASalameh Oct 21 '17 at 21:53

1 Answers1

0

You can group by your collection using month and year and then loop through the grouped items.

var articlesGrouped = context.Article
                             .Where(g=>g.CreatedTime!=null)
                             .GroupBy(x => new { Month = x.CreatedTime.Value.Month,
                                                 Year = x.CreatedTime.Value.Year })
                             .ToList();

This will give you the articles grouped by month and year.

The Month value is the number. If you want the correspnding name, you can use a DateTimeFormatInfo object.

var dtfi = new DateTimeFormatInfo();
foreach (var groupedItem in postGrouped)
{
    var month = dtfi.GetAbbreviatedMonthName(groupedItem.Key.Month)
    var year = groupedItem.Key.Year;
    //now you can loop through item 
    foreach (var article in groupedItem)
    {
        var title = article.Title;
    }
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • var articlesGrouped = context.Article .Where (g => g.CreatedTime! = null) .GroupBy (x => yeni {Ay x.CreatedTime.Value.Month, Yıl = x.CreatedTime.Value.Year}) .ToList) ; Not working :/ – i.OKTURK Oct 21 '17 at 22:11
  • What you mean "Not working" ? Are you getting an error ? What is happening ? – Shyju Oct 21 '17 at 22:18
  • 1
    Sorry I made a mistake its working Thanks a lot man – i.OKTURK Oct 21 '17 at 22:25