Dictionary get item with highest value and key

In my dictionary(int,int) I'm trying to get the key where the value is 3 and the key is the biggest. If I want to get the key where the value is 3 I can use this code:

var max = double_list.FirstOrDefault(x => x.Value == 3).Key;

But if my dictionary contains multiple items where the value is 3 I get the first item (see "FirstOrDefault") with 3, what I actually want is when there is more than one item with value 3 I want to compare the items by their key and get the item with the highest key.

For example:

| Key | Value

| 12 | 3

| 13 | 2

| 18 | 3

I want to get 18 as result, not 12. I hope you can understand what my problem is. Sorry for my bad english, any input is highly appreciated!

Jon Skeet
people
quotationmark

The simplest approach is just to use Max:

var max = dictionary.Where(x => x.Value == 3).Max(x => x.Key);

If you want to get more than just the highest key, you'd use something like:

var topTwo = dictionary.Where(x => x.Value == 3)
                       .Select(x => x.Key)
                       .OrderByDescending(x => x)
                       .Take(2);

But I'd definitely use Max if you just want the highest single key.

people

See more on this question at Stackoverflow