<p>I often have to sort a dictionary (consisting of keys &amp; values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.</p>
<p>There is a <code>SortedList</code> which is good for a single value (say frequency), that I want to map back to the word.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="noreferrer">SortedDictionary</a> orders by key, not value. Some resort to a <a href="http://www.codeproject.com/KB/recipes/lookupcollection.aspx" rel="noreferrer">custom class</a>, but is there a cleaner way?</p>

[{'answer_id': 291, 'author': 'Kalid', 'author_id': 109, 'author_profile': 'https://Stackoverflow.com/users/109', 'pm_score': 7, 'selected': False, 'text': "<p>Looking around, and using some C# 3.0 features we can do this:</p>\n\n<pre><code>foreach (KeyValuePair&lt;string,int&gt; item in keywordCounts.OrderBy(key=&gt; key.Value))\n{ \n    // do something with item.Key and item.Value\n}\n</code></pre>\n\n<p>This is the cleanest way I've seen and is similar to the Ruby way of handling hashes.</p>\n"}, {'answer_id': 292, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 6, 'selected': False, 'text': '<p>On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.</p>\n\n<p>Maybe this helps:\n<a href="http://bytes.com/forum/thread563638.html" rel="noreferrer">http://bytes.com/forum/thread563638.html</a>\nCopy/Pasting from John Timney:</p>\n\n<pre class="lang-cs prettyprint-override"><code>Dictionary&lt;string, string&gt; s = new Dictionary&lt;string, string&gt;();\ns.Add("1", "a Item");\ns.Add("2", "c Item");\ns.Add("3", "b Item");\n\nList&lt;KeyValuePair&lt;string, string&gt;&gt; myList = new List&lt;KeyValuePair&lt;string, string&gt;&gt;(s);\nmyList.Sort(\n    delegate(KeyValuePair&lt;string, string&gt; firstPair,\n    KeyValuePair&lt;string, string&gt; nextPair)\n    {\n        return firstPair.Value.CompareTo(nextPair.Value);\n    }\n);\n</code></pre>\n'}, {'answer_id': 298, 'author': 'Leon Bambrick', 'author_id': 49, 'author_profile': 'https://Stackoverflow.com/users/49', 'pm_score': 10, 'selected': True, 'text': "<p>Use:</p>\n\n<pre><code>using System.Linq.Enumerable;\n...\nList&lt;KeyValuePair&lt;string, string&gt;&gt; myList = aDictionary.ToList();\n\nmyList.Sort(\n    delegate(KeyValuePair&lt;string, string&gt; pair1,\n    KeyValuePair&lt;string, string&gt; pair2)\n    {\n        return pair1.Value.CompareTo(pair2.Value);\n    }\n);\n</code></pre>\n\n<p>Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual&nbsp;Studio&nbsp;2008 (or above).</p>\n\n<pre><code>var myList = aDictionary.ToList();\n\nmyList.Sort((pair1,pair2) =&gt; pair1.Value.CompareTo(pair2.Value));\n</code></pre>\n"}, {'answer_id': 1332, 'author': 'caryden', 'author_id': 313, 'author_profile': 'https://Stackoverflow.com/users/313', 'pm_score': 9, 'selected': False, 'text': '<p>Use LINQ:</p>\n\n<pre><code>Dictionary&lt;string, int&gt; myDict = new Dictionary&lt;string, int&gt;();\nmyDict.Add("one", 1);\nmyDict.Add("four", 4);\nmyDict.Add("two", 2);\nmyDict.Add("three", 3);\n\nvar sortedDict = from entry in myDict orderby entry.Value ascending select entry;\n</code></pre>\n\n<p>This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for <code>type-ahead</code>, you could also include <code>StartsWith</code> clause as well.</p>\n'}, {'answer_id': 382462, 'author': 'Roger Willcocks', 'author_id': 11511, 'author_profile': 'https://Stackoverflow.com/users/11511', 'pm_score': 5, 'selected': False, 'text': "<p>You'd never be able to sort a dictionary anyway.  They are not actually ordered.  The guarantees for a dictionary are that the key and value collections are iterable, and values can be retrieved by index or key, but there is no guarantee of any particular order.  Hence you would need to get the name value pair into a list.</p>\n"}, {'answer_id': 2569558, 'author': 'Alex Ruiz', 'author_id': 308018, 'author_profile': 'https://Stackoverflow.com/users/308018', 'pm_score': 2, 'selected': False, 'text': '<p>The easiest way to get a sorted Dictionary is to use the built in <code>SortedDictionary</code> class:</p>\n<pre><code>//Sorts sections according to the key value stored on &quot;sections&quot; unsorted dictionary, which is passed as a constructor argument\nSystem.Collections.Generic.SortedDictionary&lt;int, string&gt; sortedSections = null;\nif (sections != null)\n{\n    sortedSections = new SortedDictionary&lt;int, string&gt;(sections);\n}\n</code></pre>\n<p><code>sortedSections</code> will contain the sorted version of <code>sections</code></p>\n'}, {'answer_id': 2697521, 'author': 'BSalita', 'author_id': 317797, 'author_profile': 'https://Stackoverflow.com/users/317797', 'pm_score': 3, 'selected': False, 'text': '<p>Sorting a <code>SortedDictionary</code> list to bind into a <code>ListView</code> control using VB.NET:</p>\n\n<pre><code>Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)\n\nMyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)\n\nPublic Class MyDictionaryEntry \' Need Property for GridViewColumn DisplayMemberBinding\n    Public Property MyString As String\n    Public Property MyValue As Integer\nEnd Class\n</code></pre>\n\n<p>XAML:</p>\n\n<pre><code>&lt;ListView Name="MyDictionaryListView"&gt;\n    &lt;ListView.View&gt;\n        &lt;GridView&gt;\n            &lt;GridViewColumn DisplayMemberBinding="{Binding Path=MyString}" Header="MyStringColumnName"&gt;&lt;/GridViewColumn&gt;\n            &lt;GridViewColumn DisplayMemberBinding="{Binding Path=MyValue}" Header="MyValueColumnName"&gt;&lt;/GridViewColumn&gt;\n         &lt;/GridView&gt;\n    &lt;/ListView.View&gt;\n&lt;/ListView&gt;\n</code></pre>\n'}, {'answer_id': 3148631, 'author': 'mythz', 'author_id': 85785, 'author_profile': 'https://Stackoverflow.com/users/85785', 'pm_score': 4, 'selected': False, 'text': '<p>Or for fun you could use some LINQ extension goodness:</p>\n\n<pre><code>var dictionary = new Dictionary&lt;string, int&gt; { { "c", 3 }, { "a", 1 }, { "b", 2 } };\ndictionary.OrderBy(x =&gt; x.Value)\n  .ForEach(x =&gt; Console.WriteLine("{0}={1}", x.Key,x.Value));\n</code></pre>\n'}, {'answer_id': 4157151, 'author': 'sean', 'author_id': 82371, 'author_profile': 'https://Stackoverflow.com/users/82371', 'pm_score': 8, 'selected': False, 'text': '<p>You could use:</p>\n<pre><code>var ordered = dict.OrderBy(x =&gt; x.Value).ToDictionary(x =&gt; x.Key, x =&gt; x.Value);\n</code></pre>\n'}, {'answer_id': 6438343, 'author': 'Matt Frear', 'author_id': 32598, 'author_profile': 'https://Stackoverflow.com/users/32598', 'pm_score': 7, 'selected': False, 'text': '<p>You can sort a Dictionary by value and save it back to itself (so that when you foreach over it the values come out in order):</p>\n<pre><code>dict = dict.OrderBy(x =&gt; x.Value).ToDictionary(x =&gt; x.Key, x =&gt; x.Value);\n</code></pre>\n<p>Sure, it may not be correct, but it works. <a href="https://www.hyrumslaw.com/" rel="noreferrer">Hyrum\'s Law</a> means that this will very likely continue to work.</p>\n'}, {'answer_id': 11630804, 'author': 'pawan Kumar', 'author_id': 1548685, 'author_profile': 'https://Stackoverflow.com/users/1548685', 'pm_score': -1, 'selected': False, 'text': '<p>You can sort the Dictionary by value and get the result in dictionary using the code below:</p>\n\n<pre><code>Dictionary &lt;&lt;string, string&gt;&gt; ShareUserNewCopy = \n       ShareUserCopy.OrderBy(x =&gt; x.Value).ToDictionary(pair =&gt; pair.Key,\n                                                        pair =&gt; pair.Value);                                          \n</code></pre>\n'}, {'answer_id': 13854099, 'author': 'Zar Shardan', 'author_id': 913845, 'author_profile': 'https://Stackoverflow.com/users/913845', 'pm_score': 5, 'selected': False, 'text': '<p>You do not sort entries in the Dictionary. Dictionary class in .NET is implemented as a hashtable - this data structure is not sortable by definition.</p>\n\n<p>If you need to be able to iterate over your collection (by key) - you need to use SortedDictionary, which is implemented as a Binary Search Tree.</p>\n\n<p>In your case, however the source structure is irrelevant, because it is sorted by a different field. You would still need to sort it by frequency and put it in a new collection sorted by the relevant field (frequency). So in this collection the frequencies are keys and words are values. Since many words can have the same frequency (and you are going to use it as a key) you cannot use neither Dictionary nor SortedDictionary (they require unique keys). This leaves you with a SortedList.</p>\n\n<p>I don\'t understand why you insist on maintaining a link to the original item in your main/first dictionary. </p>\n\n<p>If the objects in your collection had a more complex structure (more fields) and you needed to be able to efficiently access/sort them using several different fields as keys - You would probably need a custom data structure that would consist of the main storage that supports O(1) insertion and removal (LinkedList) and several indexing structures - Dictionaries/SortedDictionaries/SortedLists. These indexes would use one of the fields from your complex class as a key and a pointer/reference to the LinkedListNode in the LinkedList as a value.</p>\n\n<p>You would need to coordinate insertions and removals to keep your indexes in sync with the main collection (LinkedList) and removals would be pretty expensive I\'d think.\nThis is similar to how database indexes work - they are fantastic for lookups but they become a burden when you need to perform many insetions and deletions.</p>\n\n<p>All of the above is only justified if you are going to do some look-up heavy processing. If you only need to output them once sorted by frequency then you could just produce a list of (anonymous) tuples:</p>\n\n<pre><code>var dict = new SortedDictionary&lt;string, int&gt;();\n// ToDo: populate dict\n\nvar output = dict.OrderBy(e =&gt; e.Value).Select(e =&gt; new {frequency = e.Value, word = e.Key}).ToList();\n\nforeach (var entry in output)\n{\n    Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);\n}\n</code></pre>\n'}, {'answer_id': 23975034, 'author': 'aggaton', 'author_id': 1575416, 'author_profile': 'https://Stackoverflow.com/users/1575416', 'pm_score': -1, 'selected': False, 'text': '<p>Given you have a dictionary you can sort them directly on values using below one liner:</p>\n\n<pre><code>var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c =&gt; c.Key, c=&gt;c.Value);\n</code></pre>\n'}, {'answer_id': 28275964, 'author': 'Akshay Kapoor', 'author_id': 4519513, 'author_profile': 'https://Stackoverflow.com/users/4519513', 'pm_score': 2, 'selected': False, 'text': '<p>Suppose we have a dictionary as:</p>\n<pre class="lang-cs prettyprint-override"><code>Dictionary&lt;int, int&gt; dict = new Dictionary&lt;int, int&gt;();\ndict.Add(21,1041);\ndict.Add(213, 1021);\ndict.Add(45, 1081);\ndict.Add(54, 1091);\ndict.Add(3425, 1061);\ndict.Add(768, 1011);\n</code></pre>\n<p>You can use temporary dictionary to store values as:</p>\n<pre class="lang-cs prettyprint-override"><code>Dictionary&lt;int, int&gt; dctTemp = new Dictionary&lt;int, int&gt;();\nforeach (KeyValuePair&lt;int, int&gt; pair in dict.OrderBy(key =&gt; key.Value))\n{\n    dctTemp.Add(pair.Key, pair.Value);\n}\n</code></pre>\n'}, {'answer_id': 31514791, 'author': 'mrfazolka', 'author_id': 3536395, 'author_profile': 'https://Stackoverflow.com/users/3536395', 'pm_score': 4, 'selected': False, 'text': '<p>You could use:</p>\n<pre><code>Dictionary&lt;string, string&gt; dic= new Dictionary&lt;string, string&gt;();\nvar ordered = dic.OrderBy(x =&gt; x.Value);\nreturn ordered.ToDictionary(t =&gt; t.Key, t =&gt; t.Value);\n</code></pre>\n'}, {'answer_id': 35645695, 'author': 'Qwertie', 'author_id': 22820, 'author_profile': 'https://Stackoverflow.com/users/22820', 'pm_score': 3, 'selected': False, 'text': '<p>The other answers are good, if all you want is to have a "temporary" list sorted by Value. However, if you want to have a dictionary sorted by <code>Key</code> that <em>automatically synchronizes</em> with another dictionary that is sorted by <code>Value</code>, you could use the <a href="http://ecsharp.net/doc/code/classLoyc_1_1Collections_1_1Bijection.html" rel="nofollow noreferrer"><code>Bijection&lt;K1, K2&gt;</code> class</a>.</p>\n\n<p><code>Bijection&lt;K1, K2&gt;</code> allows you to initialize the collection with two existing dictionaries, so if you want one of them to be unsorted, and you want the other one to be sorted, you could create your bijection with code like</p>\n\n<pre><code>var dict = new Bijection&lt;Key, Value&gt;(new Dictionary&lt;Key,Value&gt;(), \n                               new SortedDictionary&lt;Value,Key&gt;());\n</code></pre>\n\n<p>You can use <code>dict</code> like any normal dictionary (it implements <code>IDictionary&lt;K, V&gt;</code>), and then call <code>dict.Inverse</code> to get the "inverse" dictionary which is sorted by <code>Value</code>.</p>\n\n<p><code>Bijection&lt;K1, K2&gt;</code> is part of <a href="http://core.loyc.net/" rel="nofollow noreferrer">Loyc.Collections.dll</a>, but if you want, you could simply copy the <a href="https://github.com/qwertie/Loyc/blob/master/Core/Loyc.Collections/Other/Bijection.cs" rel="nofollow noreferrer">source code</a> into your own project.</p>\n\n<p><strong>Note</strong>: In case there are multiple keys with the same value, you can\'t use <code>Bijection</code>, but you could manually synchronize between an ordinary <code>Dictionary&lt;Key,Value&gt;</code> and a <a href="http://loyc.net/doc/code/classLoyc_1_1Collections_1_1BMultiMap_3_01K_00_01V_01_4.html" rel="nofollow noreferrer"><code>BMultiMap&lt;Value,Key&gt;</code></a>.</p>\n'}, {'answer_id': 54885808, 'author': 'Ashish Kamble', 'author_id': 6440372, 'author_profile': 'https://Stackoverflow.com/users/6440372', 'pm_score': 3, 'selected': False, 'text': "<p>Actually in C#, dictionaries don't have sort() methods.\nAs you are more interested in sort by values,\nyou can't get values until you provide them key.\nIn short, you need to iterate through them using LINQ's <code>OrderBy()</code>,</p>\n<pre><code>var items = new Dictionary&lt;string, int&gt;();\nitems.Add(&quot;cat&quot;, 0);\nitems.Add(&quot;dog&quot;, 20);\nitems.Add(&quot;bear&quot;, 100);\nitems.Add(&quot;lion&quot;, 50);\n\n// Call OrderBy() method here on each item and provide them the IDs.\nforeach (var item in items.OrderBy(k =&gt; k.Key))\n{\n    Console.WriteLine(item);// items are in sorted order\n}\n</code></pre>\n<p>You can do one trick:</p>\n<pre><code>var sortedDictByOrder = items.OrderBy(v =&gt; v.Value);\n</code></pre>\n<p>or:</p>\n<pre><code>var sortedKeys = from pair in dictName\n            orderby pair.Value ascending\n            select pair;\n</code></pre>\n<p>It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class).\nIf it's single you can make list of it and then apply sort.<br />\nIf it's user defined class, then that class must implement IComparable, <code>ClassName: IComparable&lt;ClassName&gt;</code> and override <code>compareTo(ClassName c)</code> as they are more faster and more object oriented than LINQ.</p>\n"}, {'answer_id': 61875551, 'author': 'Jaydeep Shil', 'author_id': 3428626, 'author_profile': 'https://Stackoverflow.com/users/3428626', 'pm_score': 2, 'selected': False, 'text': '<p>Required namespace : <code>using System.Linq;</code></p>\n\n<pre><code>Dictionary&lt;string, int&gt; counts = new Dictionary&lt;string, int&gt;();\ncounts.Add("one", 1);\ncounts.Add("four", 4);\ncounts.Add("two", 2);\ncounts.Add("three", 3);\n</code></pre>\n\n<p>Order by desc :</p>\n\n<pre><code>foreach (KeyValuePair&lt;string, int&gt; kvp in counts.OrderByDescending(key =&gt; key.Value))\n{\n// some processing logic for each item if you want.\n}\n</code></pre>\n\n<p>Order by Asc :</p>\n\n<pre><code>foreach (KeyValuePair&lt;string, int&gt; kvp in counts.OrderBy(key =&gt; key.Value))\n{\n// some processing logic for each item if you want.\n}\n</code></pre>\n'}, {'answer_id': 64841771, 'author': 'PeterK', 'author_id': 418332, 'author_profile': 'https://Stackoverflow.com/users/418332', 'pm_score': 1, 'selected': False, 'text': '<p>Sort and print:</p>\n<pre><code>var items = from pair in players_Dic\n                orderby pair.Value descending\n                select pair;\n\n// Display results.\nforeach (KeyValuePair&lt;string, int&gt; pair in items)\n{\n    Debug.Log(pair.Key + &quot; - &quot; + pair.Value);\n}\n</code></pre>\n<p>Change descending to acending to change sort order</p>\n'}, {'answer_id': 70512839, 'author': 'Franz Kurt', 'author_id': 7327114, 'author_profile': 'https://Stackoverflow.com/users/7327114', 'pm_score': 0, 'selected': False, 'text': '<p>A dictionary by definition is an unordered associative structure that contains only values and keys in a hashable way. In other words has not a previsible way to orderer a dictionary.</p>\n<p>For reference read this article from python language.</p>\n<p>Link\n<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">python data structures</a></p>\n'}, {'answer_id': 72756303, 'author': 'Vineet Agarwal', 'author_id': 7621734, 'author_profile': 'https://Stackoverflow.com/users/7621734', 'pm_score': 0, 'selected': False, 'text': '<p>Best way:</p>\n<pre><code>var list = dict.Values.OrderByDescending(x =&gt; x).ToList();\nvar sortedData = dict.OrderBy(x =&gt; list.IndexOf(x.Value));\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109/']