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

如何仅通过日期从Dictionary<DateTime, Cars>中获取对应值?

如何用纯日期提取Dictionary<DateTime, Cars>中的值?

直接用仅包含日期(无时分秒)的DateTime作为键去索引原字典是行不通的——因为字典的键是精确到时分秒的完整DateTime值,纯日期的DateTime和字典中带时分秒的键哈希值不匹配,无法直接匹配到条目。

解决方案

根据你的需求,有几种处理方式:

1. 提取当天唯一的条目

如果可以确定目标日期在字典中只有一个对应条目,用LINQ过滤键的Date属性:

var targetDate = new DateTime(2022, 6, 2);
// 找到第一个匹配日期的条目,无匹配则返回null
var targetCar = yourDictionary.FirstOrDefault(kv => kv.Key.Date == targetDate).Value;

2. 提取当天所有条目

如果目标日期可能对应多个条目,获取所有匹配项:

var targetDate = new DateTime(2022, 6, 2);
var carsOnTargetDate = yourDictionary
    .Where(kv => kv.Key.Date == targetDate)
    .Select(kv => kv.Value)
    .ToList();

3. 重构字典以支持纯日期索引

如果需要频繁按纯日期查询,建议将字典重构为以DateOnly(.NET 6+新增类型)为键的结构:

// 转换为DateOnly为键的字典(假设单日仅一个条目)
var dateKeyDictionary = yourDictionary
    .ToDictionary(kv => DateOnly.FromDateTime(kv.Key), kv => kv.Value);

// 之后可直接用纯日期索引
var targetCar = dateKeyDictionary[new DateOnly(2022, 6, 2)];

如果单日可能有多个条目,先分组再构建字典:

var dateKeyDictionary = yourDictionary
    .GroupBy(kv => DateOnly.FromDateTime(kv.Key))
    .ToDictionary(g => g.Key, g => g.Select(kv => kv.Value).ToList());

// 获取当天所有Cars
var targetCars = dateKeyDictionary[new DateOnly(2022, 6, 2)];

关键说明

DateTime的Date属性会返回一个仅保留年/月/日的新DateTime(时分秒设为00:00:00),但原字典的键是带具体时分秒的完整值,两者属于不同的键实例,因此无法直接通过索引匹配——必须通过过滤或重构字典来实现按纯日期查询。

内容的提问来源于stack exchange,提问作者tesla_coil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:18:16