I have list of next Entity "News"
class News
{
public virtual int Id { get; protected set; }
public virtual string Content { get; protected set; }
public virtual DateTime Date { get; set; }
}
Now I want to get count of them grouped by week.
This is the method I have:
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);
}
Function to get first Monday with FromDate:
public static int FirstMonday(int year)
{
int day = 0;
while ((new DateTime(year, 01, ++day)).DayOfWeek != System.DayOfWeek.Monday) ;
return day;
}
This should return me Dictionary with date of the first Day of the week and count of News for that week like:
07.03.2016 => 15,
14.03.2016 => 7,
21.03.2016 => 8,
etc...
This is not working well because it returns duplicate date keys like:
07.03.2016 => 15,
07.03.2016 => 7,
14.03.2016 => 8,
But it should be like:
07.03.2016 => 15,
14.03.2016 => 7,
21.03.2016 => 8,
I am not so good with these things, so if someone can tell me what I am doing wrong here.