In addition to Tim Schmelter's answer, you can get the date of the first day of the week, and then the group by that date.
Get the date of the first day of the week. you can use this code:
public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = dt.DayOfWeek - startOfWeek; if (diff < 0) { diff += 7; } return dt.AddDays(-1 * diff).Date; } }
then you can group by the first date of the week as follows:
var weekGroups = projects .Select(p => new { Project = p }) .GroupBy(x => x.Project.DateStart.StartOfWeek(DayOfWeek.Monday)) .Select((g, i) => new { WeekGroup = g, WeekNum = i + 1 }); foreach (var projGroup in weekGroups) { Console.WriteLine("Week " + projGroup.WeekNum); foreach(var proj in projGroup.WeekGroup) Console.WriteLine("{0} {1} {2}", proj.Project.Name, proj.Project.DateStart.ToString("d"), proj.Project.ID); }
source share