using System.Collections.Generic;
public static void Main()
new Listing { ListingDate = new DateTime(2022, 01, 05), ClosingDate = new DateTime(2022, 04, 05) },
new Listing { ListingDate = new DateTime(2022, 01, 10), ClosingDate = new DateTime(2022, 04, 10) },
new Listing { ListingDate = new DateTime(2022, 03, 01), ClosingDate = new DateTime(2022, 07, 01) },
new Listing { ListingDate = new DateTime(2022, 04, 05), ClosingDate = new DateTime(2023, 03, 07) },
var listingsByMonth = listings
return l.ListingDate.GetMonths(l.ClosingDate.AddDays(-1))
.Select(dt => new KeyValuePair<DateTime, Listing>(dt, l));
.ToLookup(kvp => kvp.Key, kvp => kvp.Value);
foreach(var g in listingsByMonth)
Console.WriteLine($"{g.Key:yyyy-MM}: {g.Count()}");
public DateTime ListingDate { get; set; }
public DateTime ClosingDate { get; set; }
public static class Extensions
public static IEnumerable<DateTime> GetMonths(this DateTime startDate, DateTime endDate)
var monthDiff = (endDate.Month - startDate.Month) + (12 * (endDate.Year - startDate.Year));
var startMonth = new DateTime(startDate.Year, startDate.Month, 1);
return Enumerable.Range(0, monthDiff + 1)
.Select(i => startMonth.AddMonths(i));