我有下一个实体“新闻”的列表
class News
{
public virtual int Id { get; protected set; }
public virtual string Content { get; protected set; }
public virtual DateTime Date { get; set; }
}
现在我想获取按周分组的数量。
这是我的方法:
public Dictionary<DateTime, int> GetCountByWeek(DateTime fromDate)
{
var vals =
from l in session.Query<News>().ToList()
where l.Date > fromDate
group l by (l.Date.DayOfYear - FirstMonday(fromDate.Year)) / 7
into gr
select new { Key = new DateTime(gr.Min(m => m.Date.Year), gr.Min(m => m.Date.Month), gr.Min(m => m.Date.Last(DayOfWeek.Monday).Day)), Value = gr.Count() };
return vals.ToDictionary(l => l.Key, l => l.Value);
}
使用 FromDate 获取第一个星期一的函数:
public static int FirstMonday(int year)
{
int day = 0;
while ((new DateTime(year, 01, ++day)).DayOfWeek != System.DayOfWeek.Monday) ;
return day;
}
这应该返回字典,其中包含一周第一天的日期以及该周的新闻计数,例如:
07.03.2016 => 15,
14.03.2016 => 7,
21.03.2016 => 8,
等等...
这不能很好地工作,因为它返回重复的日期键,例如:
07.03.2016 => 15,
07.03.2016 => 7,
14.03.2016 => 8,
但它应该是这样的:
07.03.2016 => 15,
14.03.2016 => 7,
21.03.2016 => 8,
我不太擅长这些事情,所以如果有人可以告诉我我在这里做错了什么。
最佳答案
我只是使用日期作为组键:
public Dictionary<DateTime, int> GetCountByWeek(DateTime fromDate)
{
var vals =
from l in session.Query<News>().ToList()
where l.Date > fromDate
group l by MyMonday(l.Date.Date) // Use Date.Date to ignore any time values
into gr
select new { Key = gr.Key, Value = gr.Count() };
return vals.ToDictionary(l => l.Key, l => l.Value);
}
以及 MyMonday 方法:
public static DateTime MyMonday(DateTime date)
{
var myMon = date;
while (myMon.DayOfWeek != System.DayOfWeek.Monday) {
myMon = myMon.AddDays(-1);
}
return myMon;
}
关于C# 组按日期字段列出 - 每周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185980/