如何从字典中获取最大值?

问题描述 投票:0回答:8

我有

Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();

如何获得具有

Guid
值的
MAX

c# .net linq dictionary
8个回答
133
投票

由于这是已接受的答案,我将尝试涵盖该问题的所有可能含义:

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.MaxBy(entry => entry.Value).Key; // "a"

// Note: On .NET < 6, MaxBy is not available. You can use:
var keyOfMaxValue = 
    dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; // "a"

注意:问题的关键类型为

System.Guid
。问“什么是最大的 GUID”可能没有意义,因为它们只是为了成为唯一值,而不代表任何可排序的概念。尽管如此,上述代码适用于任何支持
>
运算符的类型,为简洁起见,此处选择了
string
int


55
投票

这个效果很好。它将返回 MAX 日期的 GUID。

Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>(); 
var guidForMaxDate = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key;

12
投票
            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());

6
投票

首先对数据进行排序可能是一个解决方案。

var maxGuid = d.OrderByDescending(x => x.Value).FirstOrDefault().Key;

5
投票

Guid 实现了 IComparable,所以:

d.Keys.Max()

也不清楚为什么要这样做......


3
投票

接受的答案对我不起作用。以下代码(使用 MoreLinq)完成了这项工作:

var fooDict = new Dictionary<string, int>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var biggestInt = fooDict[keyForBiggest];

3
投票

通过在字典上使用 LINQ。

var MaximumValue = dict.FirstOrDefault(x => x.Value.Equals(dict.Values.Max()));

0
投票

另一种方法可能有助于获得单个KeyValuePair。

KeyValuePair<char, int> GuidKeyPair = guidDict.FirstOrDefault( MaxGuid => MaxGuid.Value == guidDict.Values.Max());
© www.soinside.com 2019 - 2024. All rights reserved.