我有
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
我怎样才能得到一个Guid
有价值的MAX
东西?
我有
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
我怎样才能得到一个Guid
有价值的MAX
东西?
由于这是公认的答案,我将尝试涵盖该问题的所有可能含义:
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"
注意:问题具有System.Guid
作为关键类型。问“什么是最大的 GUID”可能没有意义,因为它们只是为了成为唯一值,而不是代表任何可排序的概念。尽管如此,上面的代码将适用于任何支持>
运算符的类型,为了简洁起见,这里选择它string
。int
这很好用。它将返回 MAX 日期的 GUID。
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
var guidForMaxDate = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key;
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());
首先订购数据可能是一种解决方案。
var maxGuid = d.OrderByDescending(x => x.Value).FirstOrDefault().Key;
Guid 实现了 IComparable,因此:
d.Keys.Max()
也不清楚为什么要这样做......
通过在字典上使用 LINQ。
var MaximumValue = dict.FirstOrDefault(x => x.Value.Equals(dict.Values.Max()));
接受的答案对我不起作用。以下代码(使用 MoreLinq)完成了这项工作:
var fooDict = new Dictionary<string, int>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var biggestInt = fooDict[keyForBiggest];
另一种方法可能有助于获得 Single KeyValuePair。
KeyValuePair<char, int> GuidKeyPair = guidDict.FirstOrDefault( MaxGuid => MaxGuid.Value == guidDict.Values.Max());