Date range break with LINQ

If I have a couple of dates and I want to generate a list of all the dates between them (inclusive), I can do something like:

System.DateTime s = new System.DateTime(2010, 06, 05); System.DateTime e = new System.DateTime(2010, 06, 09); var list = Enumerable.Range(0, (e - s).Days) .Select(value => s.AddDays(value)); 

I'm stuck in having a list of date pairs that I want to explode into a list of all dates between them. Example:

 {2010-05-06, 2010-05-09}, {2010-05-12, 2010-05-15} 

should lead to

 {2010-05-06, 2010-05-07, 2010-05-08, 2010-05-09, 2010-05-12, 2010-05-13, 2010-05-14, 2010-05-15} 

Please note that date pairs are guaranteed not to overlap.

+4
source share
2 answers
 var result = listOfPairs.SelectMany(pair => Enumerable.Range(0, (pair.Item2 - pair.Item1).TotalDays) .Select(days => pair.Item1.AddDays(days))); 
+5
source

I think you could use a simple List<DateTime> to accomplish what you want.

 List<DateTime> list = new List<DateTime>(); list.AddRange(GetListDates(d1, d2)); list.AddRange(GetListDates(d3, d4)); 
0
source

Source: https://habr.com/ru/post/1307172/


All Articles