如何从字典中获取MAX值?

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"可能没有意义,因为它们只是旨在成为独特的价值,而不是代表任何可订购的概念.尽管如此,上面的代码将适用于支持>运算符的任何类型,stringint在此处选择简洁.

  • 但他要求具有最大价值的钥匙.这只是给了我们最大键,所以这是错误的. (8认同)

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)

  • 很好,虽然我会提前将 `d.Values.Max()` 放入一个变量中,否则它可能会在每次迭代中重复搜索 Max() 。 (5认同)

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)


fel*_*ult 6

首先排序您的数据可能是一个解决方案.

var maxGuid = d.OrderByDescending(x => x.Value).FirstOrDefault().Key;
Run Code Online (Sandbox Code Playgroud)


Ale*_*kov 5

Guid实现IComparable,因此:

d.Keys.Max()
Run Code Online (Sandbox Code Playgroud)

还不清楚为什么会这样做......