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

时间:2016-03-23 18:26:47

标签: c# asp.net asp.net-mvc

我有下一个实体和#34;新闻"

的列表
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,

我对这些事情不太满意,所以如果有人能告诉我这里做错了什么。

2 个答案:

答案 0 :(得分:2)

我只使用日期作为组密钥:

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;
}

答案 1 :(得分:1)

我从here借用了一个不错的扩展方法,然后像这样使用它:

public Dictionary<DateTime, int> GetCountByWeek(DateTime fromDate)
{
    Dictionary<string, int> dict = session.Query<News>().ToList()
        .Where(n => n.Date > fromDate)
        .GroupBy(n => n.StartOfWeek())
        .ToDictionary(g => g.Key, g => g.Count());


    return dict;
}

扩展方法

public static class NewsExtensions
{
    public static DateTime StartOfWeek(this News news)
    {
        int diff = news.Date.DayOfWeek - DayOfWeek.Monday;
        if (diff < 0)
        {
            diff += 7;
        }
        return news.Date.AddDays(-1 * diff).Date;
    }
}

我还没有测试过,但请试一试。