Ter*_*dor 33 .net c# linq dictionary
我有
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到一个Guid具有MAX价值?
Asi*_*sik 60
由于这是公认的答案,我将尝试涵盖问题的每个可能含义:
var dict = new Dictionary<string, int> { { "b", 3 }, { "a", 4 } };
// greatest key
var maxKey = dict.Keys.Max(); // "b"
// greatest value
var maxValue = dict.Values.Max(); // 4
// key of the greatest value
// 4 is the greatest value, and its key is "a", so "a" is the answer.
var keyOfMaxValue = dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; // "a"
Run Code Online (Sandbox Code Playgroud)
注意:问题System.Guid是关键类型.询问"什么是最大的GUID"可能没有意义,因为它们只是旨在成为独特的价值,而不是代表任何可订购的概念.尽管如此,上面的代码将适用于支持>运算符的任何类型,string并int在此处选择简洁.
Pap*_*ndy 43
这非常有效.它将返回MAX日期的GUID.
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
var guidForMaxDate = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key;
Run Code Online (Sandbox Code Playgroud)
Ste*_*n P 11
var maxGuid = Guid.Empty;
var maxDateTime = DateTime.MinValue;
foreach (var kvp in d)
{
if (kvp.Value > maxDateTime)
{
maxGuid = kvp.Key;
maxDateTime = kvp.Value;
}
}
Console.WriteLine("Guid of max date is: " + maxGuid.ToString());
Run Code Online (Sandbox Code Playgroud)
首先排序您的数据可能是一个解决方案.
var maxGuid = d.OrderByDescending(x => x.Value).FirstOrDefault().Key;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61491 次 |
| 最近记录: |