开发者

Exploding a range of dates with LINQ

开发者 https://www.devze.com 2022-12-26 23:17 出处:网络
If I have开发者_如何学Python a pair of dates, and I want to generate a list of all the dates between them (inclusive), I can do something like:

If I have开发者_如何学Python a pair 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));

What I'm stuck on is that I've got a list of pairs of dates that I want to explode into a list of all the dates between them. Example:

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

should result in

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

Note the pairs of dates are guaranteed not to overlap each other.


var result = listOfPairs.SelectMany(pair =>
                 Enumerable.Range(0, (pair.Item2 - pair.Item1).TotalDays)
                           .Select(days => pair.Item1.AddDays(days)));


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号