gpt4 book ai didi

C# 组按日期字段列出 - 每周

转载 作者:行者123 更新时间:2023-11-30 21:50:44 25 4
gpt4 key购买 nike

我有下一个实体“新闻”的列表

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com