C# 方法:将 List 分割为连续时间段并返回 Dictionary<DateTime, DateTime>

本 C# 方法将 List 中的日期时间列表分割为连续的时间段,并返回一个 Dictionary<DateTime, DateTime>,其中键值对表示每个时间段的开始时间和结束时间。

输入:

  • List:包含日期时间的列表,可能连续也可能断续。

输出:

  • Dictionary<DateTime, DateTime>:包含时间段开始时间和结束时间的字典。

逻辑:

  1. 如果输入列表为空,则返回一个包含当前时间的键值对的字典。
  2. 遍历列表,比较相邻日期时间的时间差。
  3. 如果时间差小于等于 1 秒,则认为它们属于同一个连续时间段,将结束时间更新为当前日期时间。
  4. 如果时间差大于 1 秒,则认为它们属于不同的时间段,将当前时间段的开始时间和结束时间添加到字典中,并重新设置开始时间和结束时间为当前日期时间。
  5. 遍历结束后,将最后一个时间段的开始时间和结束时间添加到字典中。

代码示例:

public Dictionary<DateTime, DateTime> GetDateTimeRanges(List<DateTime> datetimes)
{
    Dictionary<DateTime, DateTime> result = new Dictionary<DateTime, DateTime>();

    if (datetimes == null || datetimes.Count == 0)
    {
        result.Add(DateTime.Now, DateTime.Now);
        return result;
    }

    DateTime start = datetimes[0];
    DateTime end = datetimes[0];

    for (int i = 1; i < datetimes.Count; i++)
    {
        TimeSpan diff = datetimes[i] - end;
        if (diff.TotalSeconds == 1)
        {
            end = datetimes[i];
        }
        else if (diff.TotalSeconds > 1)
        {
            result.Add(start, end);
            start = datetimes[i];
            end = datetimes[i];
        }
    }

    result.Add(start, end);

    return result;
}

示例用法:

List<DateTime> datetimes = new List<DateTime>()
{
    new DateTime(2023, 4, 24, 13, 30, 44),
    new DateTime(2023, 4, 24, 13, 30, 45),
    new DateTime(2023, 4, 24, 13, 30, 46),
    new DateTime(2023, 4, 24, 13, 30, 48)
};

Dictionary<DateTime, DateTime> ranges = GetDateTimeRanges(datetimes);

foreach (var range in ranges)
{
    Console.WriteLine($'开始时间:{range.Key}, 结束时间:{range.Value}');
}

输出:

开始时间:2023-04-24T13:30:44, 结束时间:2023-04-24T13:30:48

总结:

本 C# 方法提供了一种将 List 分割为连续时间段的简单且有效的方式。该方法易于理解和实现,并能满足各种时间段分割需求。

C# 方法:将 List<DateTime> 分割为连续时间段并返回 Dictionary<DateTime, DateTime>

原文地址: https://www.cveoy.top/t/topic/oaFn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录