累积日期范围

编程入门 行业动态 更新时间:2024-10-23 20:28:30
本文介绍了累积日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我收到了日期范围的列表作为输入。其中有些是重叠,有些是 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)

更多推荐

累积日期范围

本文发布于:2023-10-27 15:39:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!