MattyMatt
MattyMatt

Reputation: 640

C# Using .Min() on a Dictionary, min value, but return a key?

I'm not sure if this is even possible, as far as I can tell, it isn't, but I have a dictionary and I want to find the Min() of values, but return either the KVP or Key. Currently I am using orderby, but I feel like that is going to be super inefficient once this grows large enough.

Upvotes: 1

Views: 2488

Answers (2)

Jim W
Jim W

Reputation: 5016

I don't think there are any shortcuts and I would think that iterating every item looking for the min would be faster than sorting it first. You could easily compare speeds to find out for sure.

-EDIT: After the comment-

If you use MoreLinq.MinBy, your code will be more concise, but you won't avoid iterating every element.

https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/MinBy.cs

So, to answer your question more explicitly, you are best to iterate every element looking for the lowest value, and when you have finished iterating all elements, return the key.

I offer this answer in case you don't want to bring in MoreLinq for any reason.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500225

You can use MoreLinq and its MinBy method:

var pair = dictionary.MinBy(x => x.Value);
var key = pair.Key;

(And yes, this is O(N) rather than O(N log N) - more efficient than ordering. It won't need as much memory, either.)

Upvotes: 5

Related Questions