字典获取具有最高值和键的项目

use*_*224 1 c# dictionary

在我的字典(int,int)中,我正在尝试获取值为3且密钥最大的密钥.如果我想获取值为3的键,我可以使用此代码:

var max = double_list.FirstOrDefault(x => x.Value == 3).Key;
Run Code Online (Sandbox Code Playgroud)

但是如果我的字典包含值为3的多个项目,我会得到第一个项目(参见"FirstOrDefault")3,我真正想要的是当有多个项目的值为3时我想通过其键来比较项目并获得具有最高键的项目.

例如:

| 钥匙| 值

| 12 | 3

| 13 | 2

| 18 | 3

我希望得到18,而不是12.我希望你能理解我的问题是什么.对不起我的英文不好,任何意见都非常感谢!

Jon*_*eet 9

最简单的方法就是使用Max:

var max = dictionary.Where(x => x.Value == 3).Max(x => x.Key);
Run Code Online (Sandbox Code Playgroud)

如果您想获得的不仅仅是最高密钥,您可以使用以下内容:

var topTwo = dictionary.Where(x => x.Value == 3)
                       .Select(x => x.Key)
                       .OrderByDescending(x => x)
                       .Take(2);
Run Code Online (Sandbox Code Playgroud)

Max如果您只想要最高的单键,我肯定会使用.