Reputation: 373
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.
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!
Upvotes: 1
Views: 3495
Reputation: 1500785
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.
Upvotes: 11
Reputation: 3914
Simply insert OrderByDescending
in your query:
var max = double_list
.OrderByDescending(x => x.Value == 3)
.FirstOrDefault().Key;
Upvotes: 0