所以我有一个
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/