c# - 在 List<Dictionary<string,string>> 中选择最小键值对,其中字典值是日期字符串

标签 c# datetime dictionary

所以我有一个

IEnumerable<Dictionary<string,string>>

通过使用获得

var differences = activeCalls.Where(l1 => !tempActiveCalls.Any(l2 => l1 == l2));

包含一个 id 作为键和一个格式为

的日期
DateTime.ToString("s") 

我想要的是获取具有最早日期的键值对。 现在我正在使用

List<Dictionary<string, DateTime>> minDate = new List<Dictionary<string, DateTime>>();
//convert strings to dates
foreach(var dictionary in differences)
{
    foreach(var kvp in dictionary)
    {
        minDate.Add(new Dictionary<string, DateTime>()
        {
            {kvp.Key, DateTime.ParseExact(kvp.Value,"yyyy'-'MM'-'dd'T'HH':'mm':'ss",null) }
        });
    }
}

将字符串转换为日期时间格式,但我坚持如何根据日期选择最小键/值对。我也不认为这根本是最简单的方法。如有任何帮助,我们将不胜感激。

最佳答案

这是一种方法,按键排序并获取第一个元素。这是因为字典实例中键的结构方式,DateTime.ToString("s") 生成可排序的日期时间字符串(其 ISO 表示法),无需将其转换为DateTime 类型。 SelectMany 会将字典实例扁平化为单个集合。使用 OrderBy 将按升序排序(从最早到最新)。

var result = differences.SelectMany(y => y).OrderBy(x => x.Key).First();

您需要在代码文件顶部包含 using System.Linq;

关于c# - 在 List<Dictionary<string,string>> 中选择最小键值对,其中字典值是日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005321/

相关文章:

java - 使用 Spring Rest 服务时在 Date 中获取错误时间

Python 2.7 - Tweepy - 如何获取 rate_limit_status()?

python - 链接两个python字典

dictionary - 修改后的 slice 元素无法通过 map 访问。我究竟做错了什么?

c# - bool ?不可为空

C# 使文本框中的一组字符表现得像一个字符

C++11 带小数秒的日期/时间

java - Java 中的 PHP strtotime()?

c# - 使用 Javascript 根据另一个控件条目验证 asp.net c# 控件

c# - 在 WinForms 中显示输入对话框