我有
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
如何获取具有MAX
值的Guid
?
我有
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
如何获取具有MAX
值的Guid
?
既然这是被接受的答案,我将尝试涵盖问题的每一个可能的意思:
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
是为了简洁明了。这个很好用。它将返回最大日期的 GUID。
Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();
var guidForMaxDate = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key;
d.Values.Max()
存储在一个变量中,否则它可能会在每次迭代中重复搜索 Max()。 - Nyerguds 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];
另一种方法可以帮助获取单个KeyValuePair。
KeyValuePair<char, int> GuidKeyPair = guidDict.FirstOrDefault( MaxGuid => MaxGuid.Value == guidDict.Values.Max());