好吧,这个任务似乎很有趣。我已经使用本地数据实现了基本功能。随意评论更多功能。你有点乱
//local data for testing
var data = new[] {
new {VideoId = "abc123",RecordindStarted = DateTime.Parse("2013-03-01 15:30:00"),RecordingEnded = DateTime.Parse("2013-03-01 15:40:00")},
new {VideoId = "def123",RecordindStarted = DateTime.Parse("2013-03-06 12:00:00"),RecordingEnded = DateTime.Parse("2013-03-06 12:40:00")},
new {VideoId = "de1223",RecordindStarted = DateTime.Parse("2013-03-06 12:30:00"),RecordingEnded = DateTime.Parse("2013-03-06 12:50:00")},
new {VideoId = "ijk123",RecordindStarted = DateTime.Parse("2013-03-10 11:00:00"),RecordingEnded = DateTime.Parse("2013-03-10 11:05:00")},
new {VideoId = "klm123",RecordindStarted = DateTime.Parse("2013-03-12 10:05:00"),RecordingEnded = DateTime.Parse("2013-03-12 10:25:00")},
new {VideoId = "klm123",RecordindStarted = DateTime.Parse("2013-03-12 10:05:00"),RecordingEnded = DateTime.Parse("2013-03-13 10:25:00")},
};
var calendar = new GregorianCalendar();
var ungroupedTotalHours = data.Select(d => GetHoursPerDays(d.RecordindStarted, d.RecordingEnded));
var groupedTotalHours =
ungroupedTotalHours.SelectMany(v => v)
.GroupBy(v=> v.Key)
.ToDictionary(v => v.Key, v => v.Sum(val => val.Value));
var result =
groupedTotalHours.GroupBy(v =>calendar.GetWeekOfYear( v.Key, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.ToDictionary(v => "Week "+ v.Key, row => row.Sum(val => val.Value));
Console.WriteLine ( string.Join(Environment.NewLine, result.Select(r => r.Key +" has "+r.Value+" hours")) );
核心逻辑转到此方法:
public IDictionary<DateTime, int> GetHoursPerDays(DateTime start, DateTime end)
{
if(end.Date == start.Date)
return new Dictionary<DateTime, int>{{start.Date, (end - start).Minutes}};
return Enumerable.Range(1, (int)(end - start).TotalHours)
.Select(v => start.AddHours(v))
.GroupBy(v => v.Date)
.ToDictionary( v => v.Key, r => r.Count());
}
印刷:
Week 9 has 10 hours
Week 10 has 65 hours
Week 11 has 44 hours