You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查DateTime时间段重叠,将变更合并到字典已有的时间段条目

时间段包含校验与合并实现方案

核心判断逻辑

新时间段完全被已有时间段包含的判定条件为:已有时间段的开始时间 ≤ 新时间段开始时间 且 已有时间段的结束时间 ≥ 新时间段结束时间。

具体实现代码

// 你的原始字典定义
Dictionary<(DateTime from, DateTime to), HashSet<string>> uniquelyChangedPeriods = new();

// 示例:待新增的时间段与对应字符串集合
var newPeriod = (from: new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc), to: new DateTime(2021, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var newContent = new HashSet<string> { "Hi", "Adress", "Something2" };

// 匹配逻辑
var matchedPeriods = uniquelyChangedPeriods.Keys
    .Where(existPeriod => 
        existPeriod.from <= newPeriod.from 
        && existPeriod.to >= newPeriod.to)
    .ToList();

if (matchedPeriods.Any())
{
    // 匹配到符合条件的条目,合并字符串集合
    foreach (var period in matchedPeriods)
    {
        uniquelyChangedPeriods[period].UnionWith(newContent);
    }
}
else
{
    // 无匹配条目,新增字典项
    uniquelyChangedPeriods.Add(newPeriod, newContent);
}

注意事项

  • 上述代码默认会将新内容合并到所有完全包含新时间段的已有条目,如果仅需要合并到第一个匹配的条目,可将Where+ToList替换为FirstOrDefault判断即可。
  • 所有存储的DateTime需保证时区统一,推荐统一使用UTC时间,避免时区差异导致时间段判断出错。

内容的提问来源于stack exchange,提问作者I am not Fat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:36:04