# 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

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>();

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;
...

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>();

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.