941

I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.

There is a SortedList which is good for a single value (say frequency), that I want to map back to the word.

SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?

jordanz
  • 367
  • 4
  • 12
Kalid
  • 22,218
  • 14
  • 44
  • 46
  • 2
    Aside from just sorting the dictionary (as in the accepted answer), you could also just create an `IComparer` that does the trick (true that it accepts a key to compare, but with a key, you can get a value). ;-) – BrainSlugs83 Mar 19 '18 at 21:16
  • 3
    @BrainSlugs83 - "create an IComparer" is not a complete solution. Please clarify how that IComparer would be **used**, to produce an ordered result. – ToolmakerSteve Aug 31 '21 at 19:51
  • 2
    Sorted dictionary doesn't make any sense as you access a dictionary by key. If you want a sorted list of all keys and values, convert it to a list, then sort it. – Yarek T Sep 29 '21 at 14:11
  • yearek T you can access in multiple ways, `ElementAt(int index)` is possible. Also you can use a `foreach` and it will iterate by index. – Barreto May 02 '23 at 20:06

21 Answers21

588

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 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 type-ahead, you could also include StartsWith clause as well.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
caryden
  • 7,738
  • 3
  • 30
  • 31
  • 18
    How can I change sortedDict back into a Dictionary? Posted new SO question here: http://stackoverflow.com/questions/3066182/c-convert-an-iorderedenumerablekeyvaluepairstring-int-into-a-dictionarystr – Kache Jun 17 '10 at 22:47
  • 1
    Sadly this does not work on VS2005 because of .net framework 2.0 there (no LINQ). It is good to have also the Bambrick's answer. – Smalcat Nov 30 '10 at 11:23
  • Great answer. And, as mentioned in other comments on other answers, be sure to include "using System.Linq;" at the top of the file. Otherwise you get somewhat confusing error messages and IntelliSense doesn't help. – Mark Meuer Nov 10 '11 at 16:56
  • 22
    I'm not sure if it always works because iterating over dictionary doesn't guarantee that KeyValuePairs are "pulled" in the same order they have been inserted. Ergo, it doesn't matter if you use orderby in LINQ because Dictionary can change order of inserted elements. It usually works as expected but there is NO GUARANTEE, especially for large dictionaries. – Bozydar Sobczak Jan 27 '12 at 08:23
  • 16
    Return type should be `IEnumerable>` or an `OrderedDictionary`. Or one should use a `SortedDictionary` from the start. For a plain `Dictionary` the MSDN clearly states "The order in which the items are returned is undefined.". It seems that @rythos42 's latest edit is to blame. :) – Boris B. Feb 07 '12 at 20:05
  • 21
    Please disregard all suggestions of `.ToDictionary` - [standard dictionaries do not guarantee a sort order](http://stackoverflow.com/a/4007787/1860652) – Alex Mar 15 '13 at 16:57
  • 1
    I just used a simple method to time this against the other top rated answer (using a `Stopwatch()`), and came out with a nearly `350%` increase in time using LINQ. Four(!) member list sorted using other method = 0.0039511 seconds; (same) four member list sorted using LINQ method = 0.0130195 seconds. – brandeded Oct 25 '13 at 14:08
  • 1
    @BorisB. I rolled back to correct version. You could have done too. Anybody can edit to make SO a better place. To all, `ToDictionary` is not a correct answer to this problem and the original answer by caryden did not have it. Happy upvoting and un-downvoting. – nawfal Nov 10 '13 at 19:28
  • For those using .NET 2.0 - have you tried using LINQBridge to fill the gap? http://www.albahari.com/nutshell/linqbridge.aspx – jocull Dec 12 '13 at 19:30
  • Calling '.ToDictionary(pair => pair.Key, pair => pair.Value); ' results in an unordered dictionary. As the other comments suggest this is not correct. – steven87vt Sep 19 '17 at 21:36
  • I like the final form of this answer for the flexibility it offers. For instance if you want just a list of reordered keys, you just change the select to: select entry.Key – Larry Smith Feb 17 '19 at 19:30
572

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

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 Studio 2008 (or above).

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leon Bambrick
  • 26,009
  • 9
  • 51
  • 75
  • 27
    I used this solution (Thanks!) but was confused for a minute until I read Michael Stum's post (and his code snippet from John Timney) and realised that myList is a secondary object, a list of KeyValuePairs, which is created from the dictionary, and then sorted. – Robin Bennett Mar 31 '09 at 13:33
  • 3
    sorry but this answer was difficult to understand as im not familiar with the delegate keyword (maybe different in vb), n it isn't clear where the sorting is happening as you'd either need to run number of item multiplied by number of items (no of items squared) comparisons by searching/comparing each element to the whole dictionary for each element, or if you are doing just comparing between current n last then you'd need to do that in more than one loop over the collection, which is why i didnt 'get it' as is. maybe more info on where the sorting n reordering is occuring woulda been helpful! – Erx_VB.NExT.Coder Sep 12 '10 at 15:07
  • 117
    it it's one liner - You don't need braces. it can be rewritten as `myList.Sort((x,y)=>x.Value.CompareTo(y.Value));` – Arnis Lapsa Sep 26 '10 at 16:40
  • 1
    How would this delegate statement in the sorting method look in VB.NET? – Jonas Nov 02 '10 at 12:56
  • 1
    I know this is two years later...but I'm sure this could help someone in lieu of the previous comment: myList.Sort(Function(firstPair As KeyValuePair(Of String, String), nextPair As KeyValuePair(Of String, String)) firstPair.Value.CompareTo(nextPair.Value)) – sacredfaith Jun 05 '12 at 19:15
  • 27
    To sort descending switch the x and the y on the comparison: myList.Sort((x,y)=>y.Value.CompareTo(x.Value)); – Arturo Oct 16 '12 at 22:43
  • 8
    I think it's worth noting that this requires Linq for the ToList extension method. – Ben Oct 15 '14 at 23:41
  • 37
    You guys are waaaay over complicating this -- a dictionary already implements `IEnumerable`, so you can get a sorted list like this: `var mySortedList = myDictionary.OrderBy(d => d.Value).ToList();` – BrainSlugs83 Mar 19 '18 at 21:12
  • I found there is no need for ToList(). You can create a List with another collection, so: var l = new List>( aDictionary ); – Baltasarq Apr 09 '19 at 11:31
359

You could use:

var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
sean
  • 11,164
  • 8
  • 48
  • 56
  • 43
    This is a good solution, but it should have this right before the ending semi-colon: .ToDictionary(pair => pair.Key, pair => pair.Value); – theJerm Mar 30 '12 at 17:55
  • I prefer this one, clean and simple. @Gravitas: I agree, and framework version was not mentioned in the OP. – Andreas Nov 22 '12 at 10:34
  • Because it requires a cast back to dictionary which is not always straight forward... – MoonKnight Apr 24 '13 at 15:02
  • 6
    @theJerm by putting the sorted items back to a dictionary is the order guaranteed then? It might work today, but it's not guaranteed. – nawfal Oct 31 '13 at 07:41
  • 3
    Using the 4.5 framework, just verified that it does *not* require a cast back to dictionary. – Jagd Jun 26 '14 at 19:36
  • 20
    There should not be a cast back to a dictionary because dictionaries are not ordered. There's no guarantee the KeyValuePairs will stay in the order you want. – David DeMar Nov 19 '14 at 14:54
185

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):

dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

Sure, it may not be correct, but it works. Hyrum's Law means that this will very likely continue to work.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Matt Frear
  • 52,283
  • 12
  • 78
  • 86
  • 13
    You can also use OrderByDescending if you want to sort into a descending list. – Mendokusai Aug 17 '11 at 02:16
  • Worked for me, although I had to change it slightly to: Dictionary dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); – Josh Dec 15 '11 at 09:34
  • 22
    This "working" is not guaranteed. Its an implementation detail. It need not work other times. Wrong answer, downvoted. – nawfal Apr 30 '14 at 13:45
  • 6
    The Dictionary output is NOT guaranteed to have any particular sort order. – Roger Willcocks Mar 24 '15 at 02:12
  • 7
    I would be quite concerned to see this in production code. It is not guaranteed and could change at any time. Not that I shy away from pragmatic solutions, it just shows a lack of understanding of the data structure imo. – jamespconnor Apr 28 '15 at 13:24
  • I think this WILL work, if items are added to dictionary at the same time and nothing is removed/modified. is there any evidence that .NET will re-order items in dictionary? – AaA Oct 26 '15 at 03:50
  • 1
    `var temp_enumerated_once_never_modified = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);` There its fixed and works. – mxmissile Jan 08 '19 at 19:31
  • 4
    @mxmissile - While that "works", given that Dictionary does not guarantee order, you should have omitted `.ToDictionary(...)`. That turns it back into a dictionary. `dict.OrderBy(...)` is all that should be done; that yields an enumerator, as desired. – ToolmakerSteve Aug 31 '21 at 19:46
  • In the linked description of Hyrum's law, Hyrum wrote: "The above observation grew out of experiences when even the simplest library change caused failures in some far off system." I think it's better not to introduce more potential failures into the system. – Neil Feb 15 '23 at 06:26
178

Looking around, and using some C# 3.0 features 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 way I've seen and is similar to the Ruby way of handling hashes.

Alexander
  • 2,320
  • 2
  • 25
  • 33
Kalid
  • 22,218
  • 14
  • 44
  • 46
  • 7
    Don't forget to add the System.Linq namespace when using this syntax. – sourcenouveau Jun 07 '10 at 15:10
  • 4
    `(for KeyValuePair item in keywordCounts.OrderBy(key => key.Value) select item).ToDictionary(t => t.Key, t => t.Value)` - just a small addition to your answer :) Thanks, btw :) – Andrius Naruševičius Sep 21 '12 at 07:17
  • 10
    @AndriusNaruševičius: If you add the resulting items back into a dictionary, you will destroy the order, as [dictionaries are not guaranteed to be ordered in any particular fashion](http://stackoverflow.com/a/4007787/1430156). – O. R. Mapper Jan 24 '15 at 10:25
66

On a high level, you have no other choice than to walk through the whole Dictionary and look at each value.

Maybe this helps: 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);
    }
);
Palle Due
  • 5,929
  • 4
  • 17
  • 32
Michael Stum
  • 177,530
  • 117
  • 400
  • 535
  • 2
    Perfect non-Linq solution. It never ceases to amaze me how people feel the need to use Linq even when it's absolutely not required to solve the problem. With C# 3, I believe you can also simplify the Sort to just use a lambda: myList.Sort((x, y) => x.Value.CompareTo(y.Value)); –  Jul 06 '16 at 01:28
29

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.

Roger Willcocks
  • 1,649
  • 13
  • 27
  • 3
    A sorted dictionary could yield a list of key-value pairs though. – recursive Dec 20 '08 at 05:19
  • 2
    @recursive Any dictionary should yield that. Interesting to note that my answer, which is correct, but incomplete (could have done what the better examples did) is voted below an invalid answer that would result in exceptions on duplicate values in the original dictionary (keys are unique, values are not guaranteed to be) – Roger Willcocks Jul 07 '10 at 05:30
  • 5
    This is the bes answer, because Dictionary is not sortable. It hashes Keys and you can perform an extremely fast seek operation on it. – Paulius Zaliaduonis Aug 24 '11 at 09:09
  • @NetMage Yes. But the other part of the problem is that they wanted ordered by Value. And you could only do that by swapping Key and Value. And Value is not necessarily unique, but Key must be. – Roger Willcocks Sep 29 '19 at 02:32
  • 1
    Yes, but I think your answer is incorrect because of the absolute statements in it. – NetMage Sep 30 '19 at 19:45
  • @NetMage And the OP stated that SortedDictionary wasn't suitable. – Roger Willcocks Oct 01 '19 at 22:32
26

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.

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.

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.

I don't understand why you insist on maintaining a link to the original item in your main/first dictionary.

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.

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

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:

var dict = new SortedDictionary<string, int>();
// ToDo: populate dict

var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();

foreach (var entry in output)
{
    Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
Zar Shardan
  • 5,675
  • 2
  • 39
  • 37
  • 1
    This is actually the best answer, from a Computer Science perspective. It's not the simplest or the fastest, and it requires one to evaluatethe actual problem at hand, instead of trying to give a non existent "quick recipe". I suppose that many programmers are OK with a solution that "seems to work". Until it doesn't. I wish that many would know better... – Alberto Chiesa Jun 09 '22 at 07:18
  • it was worthful for me to reach here (end). – Gray Programmerz Jul 03 '22 at 16:53
14

You could use:

Dictionary<string, string> dic= new Dictionary<string, string>();
var ordered = dic.OrderBy(x => x.Value);
return ordered.ToDictionary(t => t.Key, t => t.Value);
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
mrfazolka
  • 780
  • 1
  • 7
  • 24
12

Or for fun you could use some LINQ extension goodness:

var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
  .ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));
mythz
  • 141,670
  • 29
  • 246
  • 390
10

Sorting a SortedDictionary list to bind into a ListView control using VB.NET:

Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)

MyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)

Public Class MyDictionaryEntry ' Need Property for GridViewColumn DisplayMemberBinding
    Public Property MyString As String
    Public Property MyValue As Integer
End Class

XAML:

<ListView Name="MyDictionaryListView">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=MyString}" Header="MyStringColumnName"></GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=MyValue}" Header="MyValueColumnName"></GridViewColumn>
         </GridView>
    </ListView.View>
</ListView>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BSalita
  • 8,420
  • 10
  • 51
  • 68
6

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 Key that automatically synchronizes with another dictionary that is sorted by Value, you could use the Bijection<K1, K2> class.

Bijection<K1, K2> 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

var dict = new Bijection<Key, Value>(new Dictionary<Key,Value>(), 
                               new SortedDictionary<Value,Key>());

You can use dict like any normal dictionary (it implements IDictionary<K, V>), and then call dict.Inverse to get the "inverse" dictionary which is sorted by Value.

Bijection<K1, K2> is part of Loyc.Collections.dll, but if you want, you could simply copy the source code into your own project.

Note: In case there are multiple keys with the same value, you can't use Bijection, but you could manually synchronize between an ordinary Dictionary<Key,Value> and a BMultiMap<Value,Key>.

Azrael
  • 175
  • 1
  • 12
Qwertie
  • 16,354
  • 20
  • 105
  • 148
  • Similar to [http://stackoverflow.com/questions/268321](http://stackoverflow.com/questions/268321) but can replace each Dictionary with SortedDictionary. Although the answers look not to support duplicate values (assumes 1 to 1). – crokusek Jul 11 '16 at 23:35
6

Actually in C#, dictionaries don't have sort() methods. As you are more interested in sort by values, you can't get values until you provide them key. In short, you need to iterate through them using LINQ's OrderBy(),

var items = new Dictionary<string, int>();
items.Add("cat", 0);
items.Add("dog", 20);
items.Add("bear", 100);
items.Add("lion", 50);

// Call OrderBy() method here on each item and provide them the IDs.
foreach (var item in items.OrderBy(k => k.Key))
{
    Console.WriteLine(item);// items are in sorted order
}

You can do one trick:

var sortedDictByOrder = items.OrderBy(v => v.Value);

or:

var sortedKeys = from pair in dictName
            orderby pair.Value ascending
            select pair;

It also depends on what kind of values you are storing: single (like string, int) or multiple (like List, Array, user defined class). If it's single you can make list of it and then apply sort.
If it's user defined class, then that class must implement IComparable, ClassName: IComparable<ClassName> and override compareTo(ClassName c) as they are more faster and more object oriented than LINQ.

Tanjim Ahmed Khan
  • 650
  • 1
  • 9
  • 21
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
3

Suppose we have a dictionary as:

Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(21,1041);
dict.Add(213, 1021);
dict.Add(45, 1081);
dict.Add(54, 1091);
dict.Add(3425, 1061);
dict.Add(768, 1011);

You can use temporary dictionary to store values as:

Dictionary<int, int> dctTemp = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))
{
    dctTemp.Add(pair.Key, pair.Value);
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Akshay Kapoor
  • 185
  • 1
  • 3
3

Required namespace : using System.Linq;

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

Order by desc :

foreach (KeyValuePair<string, int> kvp in counts.OrderByDescending(key => key.Value))
{
// some processing logic for each item if you want.
}

Order by Asc :

foreach (KeyValuePair<string, int> kvp in counts.OrderBy(key => key.Value))
{
// some processing logic for each item if you want.
}
Jaydeep Shil
  • 1,894
  • 22
  • 21
2

The easiest way to get a sorted Dictionary is to use the built in SortedDictionary class:

//Sorts sections according to the key value stored on "sections" unsorted dictionary, which is passed as a constructor argument
System.Collections.Generic.SortedDictionary<int, string> sortedSections = null;
if (sections != null)
{
    sortedSections = new SortedDictionary<int, string>(sections);
}

sortedSections will contain the sorted version of sections

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
Alex Ruiz
  • 93
  • 1
  • 1
  • 11
    As you mention in your comment, `SortedDictionary` sorts by keys. The OP wants to sort by value. `SortedDictionary` doesn't help in this case. – Marty Neal Sep 12 '12 at 15:50
  • Well... If he/she (you) can, just set the values as the keys. I timed the operations and `sorteddictionary()` always won out by at least 1 microsecond, and it's much easier to manage (as the overhead of converting it back into something easily interacted with and managed similarly to a Dictionary is 0 (it is already a `sorteddictionary`)). – brandeded Oct 25 '13 at 14:17
  • 7
    @mbrownnyc - nope, doing that requires the assumption or precondition that the VALUES are unique, which is not guaranteed. – Roger Willcocks Mar 24 '15 at 02:14
1

Sort and print:

var items = from pair in players_Dic
                orderby pair.Value descending
                select pair;

// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
    Debug.Log(pair.Key + " - " + pair.Value);
}

Change descending to acending to change sort order

PeterK
  • 4,243
  • 4
  • 44
  • 74
1

The following code snippet sorts a Dictionary by values.

The code first creates a dictionary and then uses OrderBy method to sort the items.

public void SortDictionary()  
{  
  
    // Create a dictionary with string key and Int16 value pair  
    Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();  
    AuthorList.Add("Mahesh Chand", 35);  
    AuthorList.Add("Mike Gold", 25);  
    AuthorList.Add("Praveen Kumar", 29);  
    AuthorList.Add("Raj Beniwal", 21);  
    AuthorList.Add("Dinesh Beniwal", 84);   
  
    // Sorted by Value  
  
    Console.WriteLine("Sorted by Value");  
    Console.WriteLine("=============");  
    foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Value))  
    {  
        Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);  
    }  
} 
Abbas Aryanpour
  • 391
  • 3
  • 15
0

Best way:

var list = dict.Values.OrderByDescending(x => x).ToList();
var sortedData = dict.OrderBy(x => list.IndexOf(x.Value));
-2

You can sort the Dictionary by value and get the result in dictionary using the code below:

Dictionary <<string, string>> ShareUserNewCopy = 
       ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,
                                                        pair => pair.Value);                                          
Tisho
  • 8,320
  • 6
  • 44
  • 52
  • 8
    By putting the sorted items back into a dictionary, they are no longer guaranteed to be sorted when you enumerate the new dictionary. – Marty Neal Sep 12 '12 at 15:48
  • 3
    And why are you adding this answer when this is already answered? – nawfal Oct 31 '13 at 07:42
-2

Given you have a dictionary you can sort them directly on values using below one liner:

var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);
aggaton
  • 3,066
  • 2
  • 25
  • 36
  • 4
    This answer is incorrect, as [the resulting dictionary is not guaranteed to be ordered.](http://stackoverflow.com/a/4007787/1430156) – O. R. Mapper Jan 24 '15 at 10:22