本文介绍了累积日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到了日期范围的列表作为输入。其中有些是重叠,有些是 adjacent 。是否有任何集合会累积传入日期范围?
I recieve as input a list of date ranges. Some of them are overlapping, some are adjacent. Is there any collection that would accumulate the incoming date ranges?
例如:
(2018/01/01, 2018/01/02), (2018/02/15, 2018/03/21), (2018/01/10, 2018/01/10), (2018/01/03, 2018/01/09)结果:
(2018/01/01, 2018/01/10), // 1st, 3rd, 4th lines combined (2018/02/15, 2018/03/21) // 2nd line推荐答案
在标准库中没有此类集合。但是,您可以为其实现自定义的简单方法;前提是期间为 Tuple< DateTime,DateTime> :
No there are no such collections in the standard library. However, you can implement a custom simple method for it; providing that the period is Tuple<DateTime, DateTime>:
private static IEnumerable<Tuple<DateTime, DateTime>> Accumulate( IEnumerable<Tuple<DateTime, DateTime>> source) { var data = source .OrderBy(date => date.Item1) .ThenByDescending(date => date.Item2); DateTime left = DateTime.MinValue; // make compiler be happy: initialization DateTime right = DateTime.MinValue; // -/- bool first = true; foreach (var item in data) { if (first) { left = item.Item1; right = item.Item2; first = false; } else if (right.AddDays(1) >= item.Item1) // can be combined; keep on combining right = item.Item2 > right ? item.Item2 : right; else { // can't be combined: return previous chunk yield return Tuple.Create(left, right); // start a new chunk left = item.Item1; right = item.Item2; } } // if we have a very last chunk to return, do it if (!first) yield return Tuple.Create(left, right); }然后
Tuple<DateTime, DateTime>[] test = new Tuple<DateTime, DateTime>[] { Tuple.Create(new DateTime(2018, 01, 01), new DateTime(2018, 01, 02)), Tuple.Create(new DateTime(2018, 02, 15), new DateTime(2018, 03, 21)), Tuple.Create(new DateTime(2018, 01, 10), new DateTime(2018, 01, 10)), Tuple.Create(new DateTime(2018, 01, 03), new DateTime(2018, 01, 09)), }; var result = Accumulate(test) .ToList(); string report = string.Join("," + Environment.NewLine, result .Select(item => $"({item.Item1:yyyy'/'MM'/'dd}, {item.Item2:yyyy'/'MM'/'dd})")); Console.Write(report);结果
(2018/01/01, 2018/01/10), (2018/02/15, 2018/03/21)更多推荐
累积日期范围
发布评论