我收到了输入日期范围的列表。其中有些是重叠的,有些是相邻的。是否有任何可以累积输入日期范围的集合?
例如。:
(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>
:
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)
关于c# - 累积日期范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52499143/