我有一个场景,我需要检索按日期时间字段的月份分组的对象数。
我发现以下帖子让我了解了那条路......
Linq: group by year and month, and manage empty months
...但是我需要列出今天的前12个月以及每个月的对象数量,这是我正在努力的地方。
我已经看过其他一些有类似问题/解决方案的帖子,但我选择了上面的一个,因为它也是要求在任意月份产生0的记录。
感谢您提供任何帮助。
修改
好的,我得到了一点感谢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;
}
}
......看起来效率很低......我不禁想到必须有比这更好的方法。我是在正确的轨道上吗?
答案 0 :(得分:2)
这应该适合你:
var now = DateTime.Now;
var last = new DateTime(now.Year, now.Month, 1);
var first = last.AddMonths(-12);
var query =
from s in somethings
where s.DateTimeField >= first
where s.DateTimeField < last
select new
{
Month = new DateTime(s.DateTimeField.Year, s.DateTimeField.Month, 1),
Something = s,
};
var lookup = query.ToLookup(x => x.Month, x => x.Something);
var counts =
from n in Enumerable.Range(-12, 12)
let Month = last.AddMonths(n)
select new
{
Month,
Count = lookup[Month].Count(),
};
你可能需要稍微摆弄它,但结构应该是合理的。