1
我有一个场景,我需要检索按日期时间字段的月份分组的对象计数。Linq - 按前12个月的日期时间组 - 包括空月
我发现下面的帖子里面让我的存在方式的一部分...
Linq: group by year and month, and manage empty months
...但我需要列出从今天的日期前12个月和对象为计数每个月,这是我挣扎的地方。
我见过几个其他职位类似问题/解决方案,但我选择了,因为它也产生任何个月的记录与任何帮助的0
感谢计数的要求,上述一个我可以得到这个。
编辑
OK,我远一点感谢Enigmativity(感谢您抽出宝贵的时间!):
var news = from s in db.NewsItems
where s.SubmittedDate > first
select new
{
Date = s.SubmittedDate,
Title = s.Title,
};
var grouping = from g in news.AsEnumerable()
select new NewsCountCollection
(
g.Date,
g.Title
);
var lookup = grouping.ToLookup(x => x.Month, x => x.Title);
var counts = from n in Enumerable.Range(-11, 12)
let Month = last.AddMonths(n)
select new
{
Month,
Count = lookup[Month].Count(),
};
var countList = from c in counts.AsEnumerable()
select new NewsCountMonthList
(
c.Month.ToString("MMMM"),
c.Count
);
...及以下
public class NewsCountCollection
{
public DateTime Month { get; set; }
public string Title { get; set; }
public NewsCountCollection(DateTime date, string title)
{
this.Month = new DateTime(date.Year, date.Month, 1);
this.Title = title;
}
}
public class NewsCountMonthList
{
public string Month { get; set; }
public int Count { get; set; }
public NewsCountMonthList(string month, int count)
{
this.Month = month;
this.Count = count;
}
}
......虽然似乎效率很低......但我不禁想到必须有比这更好的方法。我在正确的轨道上吗?
请发布您尝试过的代码,您正在处理的对象结构以及任何示例数据。 –