Just how do you arrange a dictionary by value?

I usually need to arrange a dictionary, containing keys & values, by value. As an example, I have a hash of words and also corresponding regularities, that I intend to get by regularity.

There is a SortedList which benefits a solitary value (claim regularity), that I intend to map it back to words.

SortedDictionary orders by key, not value. Some consider a custom class, yet exists a cleaner means?

0
2019-05-03 18:08:42
Source Share
Answers: 4

On a high degree, you have nothing else selection after that to go through the entire Dictionary and also consider each value.

Possibly this aids : http://bytes.com/forum/thread563638.html. Copy/Pasting from John Timney :

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");

List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
    delegate(KeyValuePair<string, string> firstPair,
    KeyValuePair<string, string> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);
.
0
2019-05-07 17:16:14
Source

Looking about, and also making use of some C# 3.0 attributes we can do this :

foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{ 
    // do something with item.Key and item.Value
}

This is the cleanest means I've seen and also resembles the Ruby means of taking care of hashes.

0
2019-05-07 17:05:56
Source

Use :

using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();

myList.Sort(
    delegate(KeyValuePair<string, string> pair1,
    KeyValuePair<string, string> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
);

Given that you're targeting.NET 2.0 or above, you can streamline this right into lambda syntax-- it's equal, yet much shorter. If you're targeting.NET 2.0 you can just utilize this syntax if you're making use of the compiler from Visual Studio 2008 (or above ).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
0
2019-05-07 16:35:51
Source

Use LINQ :

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

This would certainly additionally permit wonderful adaptability because you can select the leading 10, 20 10%, and so on. Or if you are utilizing your word regularity index for type-ahead, you can additionally include StartsWith condition too.

0
2019-05-07 16:32:34
Source