如何使用实体框架对按月分组的日期进行日期 [英] How to Datetime Groupby Month with Entity Framework
本文介绍了如何使用实体框架对按月分组的日期进行日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码在这里:
var query = context.Article.GroupBy(x=>x.CreateDate.Value.Month)
不起作用
例如
January 2017
February 2017
March 2017
推荐答案
您可以使用月份和年份对集合进行分组,然后循环浏览分组的项目.
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.
月份值是数字.如果需要相应的名称,可以使用DateTimeFormatInfo
对象.
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;
}
}
这篇关于如何使用实体框架对按月分组的日期进行日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文