// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Linq; namespace E { public struct DateRange { public DateTime First; public DateTime Last; public override string ToString() { return string.Format("[{0} - {1}]", First.ToShortDateString(), Last.ToShortDateString()); } } public static class DateRangeUtil { public static List Expand(DateRange range) { List res = new List(); for(DateTime dt = range.First; dt <= range.Last; dt = dt.AddDays(1)) res.Add(dt); return res; } public static DateRange Collapse(List list) { return new DateRange { First = list[0], Last = list[list.Count - 1] }; } public static List Group(DateRange range, Func eval) { return Expand(range).GroupBy(dt => eval(dt)).Select(g => new DateRange { First = g.Min(), Last = g.Max() }).ToList(); } public static List GroupByYear(DateRange range) { return Group(range, dt => dt.Year); } public static List GroupByMonth(DateRange range) { return Group(range, dt => 12 * dt.Year + dt.Month); } } public class Program { public static void Main(string[] args) { DateRange all = new DateRange { First = new DateTime(2013, 1, 1), Last = new DateTime(2013,12,31) }; Console.WriteLine(all); foreach(DateRange dr in DateRangeUtil.GroupByMonth(all)) { Console.WriteLine(dr); } } } }