gpt4 book ai didi

c# - 获取连续的日期范围

转载 作者:可可西里 更新时间:2023-11-01 09:08:01 25 4
gpt4 key购买 nike

给定一个日期范围列表,我想获得一个连续日期范围的列表。

enter image description here

我不太确定我正在寻找的术语,但我整理了一个框架:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ContiguousTimeSpans
{
class Program
{
static void Main(string[] args)
{
List<DateRange> ranges = new List<DateRange>();
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 07:00:00"), DateTime.Parse("01/12/2015 10:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 06:00:00"), DateTime.Parse("01/12/2015 09:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 05:00:00"), DateTime.Parse("01/12/2015 08:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 18:00:00"), DateTime.Parse("01/12/2015 21:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 12:00:00"), DateTime.Parse("01/12/2015 14:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 20:00:00"), DateTime.Parse("01/12/2015 22:00:00")));
ranges.Add(new DateRange(DateTime.Parse("01/12/2015 11:00:00"), DateTime.Parse("01/12/2015 23:00:00")));

List<DateRange> contiguousBlocks = GetContiguousTimespans(ranges);
Debug.Assert(contiguousBlocks.Count == 2);

Debug.Assert(contiguousBlocks[0].Start.Hour == 5);
Debug.Assert(contiguousBlocks[0].End.Hour == 10);

Debug.Assert(contiguousBlocks[1].Start.Hour == 11);
Debug.Assert(contiguousBlocks[1].End.Hour == 23);

Console.ReadKey();
}

public static List<DateRange> GetContiguousTimespans(List<DateRange> ranges)
{
List<DateRange> result = new List<DateRange>();
//???
return result;
}
}

public class DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }

public DateRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
}
}

有没有办法推断出连续的范围?

最佳答案

不确定我是否完全理解这一点,但是关于所写的内容和测试数据这应该有效:

public static List<DateRange> GetContiguousTimespans(List<DateRange> ranges)
{
List<DateRange> result = new List<DateRange>();
ranges.Sort((a,b)=>a.Start.CompareTo(b.Start));
DateRange cur = ranges[0];

for (int i = 1; i < ranges.Count; i++)
{
if (ranges[i].Start <= cur.End)
{
if (ranges[i].End >= cur.End)
cur.End = ranges[i].End;
}
else
{
result.Add(cur);
cur = ranges[i];
}
}

result.Add(cur);

return result;
}

当然这也需要添加一些边界值的检查,但我想总体思路应该很清楚。

关于c# - 获取连续的日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com