Dezzamondo
Dezzamondo

Reputation: 2318

c# dictionary get the key of the min value

probably a simple one for you today but I'm currently going round in circles. Consider this scenario:

var tempDictionary = new Dictionary<string, int>();
tempDictionary.Add("user 1", 5);
tempDictionary.Add("user 2", 3);
tempDictionary.Add("user 3", 5);

Console.WriteLine(tempDictionary.Min(x => x.Key) + " => " tempDictionary.Min(x => x.Value);

The above returns "user 1 => 3".

How would you go about returning the key with the lowest value in a dictionary? The output I'm after would look like this instead: "user2 => 3"

Any ideas?

Upvotes: 26

Views: 46757

Answers (5)

Andrea C
Andrea C

Reputation: 329

I had a similar issue and I preferred not ordering the values of the dictionary, but simply find the min with a single iteration (ordering is > O(N)). You may need to guard against corner cases and similar.

    var s = String.Empty;
    var min = Int32.MaxValue;
    foreach (var item in tempDictionary) {
        if (item.Value < min){
            s = item.Key;
            min = item.Value;
        }
    }

    Console.WriteLine(s + " => " + min);

Upvotes: 0

sharno
sharno

Reputation: 720

Sorting is less efficient as it takes O(n log n) but choosing the minimum should be just O(n).

I think this is an easier way:

tempDictionary.Where(e => e.Value == tempDictionary.Min(e2 => e2.Value)).First()

using this you can even get all minimum values if you just remove .First()

Upvotes: 2

Muna
Muna

Reputation: 41

Try this one :
var val = tempDictionary.OrderBy(k => k.Value).FirstOrDefault(); Console.WriteLine(val.Key +" => "+val.Value);

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222572

using morelinq

var keyR = tempDictionary.MinBy(kvp => kvp.Value).Key;

or

 var min = tempDictionary.Aggregate((l, r) => l.Value < r.Value ? l : r).Key;

from Highest value of a Dictionary in C#

Upvotes: 39

spender
spender

Reputation: 120420

var keyAndValue = tempDictionary.OrderBy(kvp => kvp.Value).First();
Console.WriteLine("{0} => {1}", keyAndValue.Key, keyAndValue.Value);

If your dataset is non-trivial in size, you might consider the MinBy extension in moreLinq. Here's an implementation hosted on SO.

Upvotes: 18

Related Questions