标签云

微信群

扫码加入我们

WeChat QR Code

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 it back to the word.SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?


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

2019年03月23日40分46秒

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 thedictionary, and then sorted.

2019年03月24日40分46秒

it it's one liner - You don't need braces. it can be rewritten as myList.Sort((x,y)=>x.Value.CompareTo(y.Value));

2019年03月23日40分46秒

To sort descending switch the x and the y on the comparison:myList.Sort((x,y)=>y.Value.CompareTo(x.Value));

2019年03月24日40分46秒

I think it's worth noting that this requires Linq for the ToList extension method.

2019年03月23日40分46秒

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

2019年03月23日40分46秒

How can I change sortedDict back into a Dictionary<string, int>? Posted new SO question here: stackoverflow.com/questions/3066182/…

2019年03月23日40分46秒

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.

2019年03月23日40分46秒

I'm not sure if it always works because iterating over dictionary doesn't guaranteethat 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.

1970年01月01日00分03秒

Return type should be IEnumerable<KeyValuePair<TKey, TValue>> or an OrderedDictionary<TKey, TValue>. 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. :)

2019年03月24日40分46秒

Please disregard all suggestions of .ToDictionary - standard dictionaries do not guarantee a sort order

2019年03月23日40分46秒

I'm not sure why this solution is not more popular - perhaps because it requires .NET 3.5?

1970年01月01日00分03秒

This is a good solution, but it should have this right before the ending semi-colon: .ToDictionary(pair => pair.Key, pair => pair.Value);

2019年03月24日40分46秒

theJerm: not true

2019年03月23日40分46秒

theJerm by putting the sorted items back to a dictionary is the order guaranteed then? It might work today, but it's not guaranteed.

2019年03月23日40分46秒

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.

2019年03月24日40分46秒

I was trying to sort a dictionary while adding the KeyValuePairs to a ComboBox... this worked great! Thanks!

2019年03月23日40分46秒

Don't forget to add the System.Linq namespace when using this syntax.

2019年03月23日40分46秒

(for KeyValuePair<string, int> 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 :)

2019年03月24日40分46秒

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.

2019年03月24日40分46秒

This was handy. How can it be inverted to go the other way?

2019年03月24日40分46秒

You can also use OrderByDescending if you want to sort into a descending list.

2019年03月23日40分46秒

Incorrect: stackoverflow.com/a/4007787/1860652

2019年03月24日40分46秒

This "working" is not guaranteed. Its an implementation detail. It need not work other times. Wrong answer, downvoted.

2019年03月24日40分46秒

The Dictionary output is NOT guaranteed to have any particular sort order.

2019年03月23日40分46秒

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.

2019年03月24日40分46秒

stringnextPair -> string> nextPairstringfirstPair -> string> firstPair

2019年03月23日40分46秒

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

2019年03月23日40分46秒

A sorted dictionary could yield a list of key-value pairs though.

2019年03月24日40分46秒

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

2019年03月24日40分46秒

This is the bes answer, because Dictionary is not sortable. It hashes Keys and you can perform an extremely fast seek operation on it.

2019年03月24日40分46秒

Also incorrect. See here: stackoverflow.com/a/4007787/463828

2019年03月24日40分46秒

As you mention in your comment, SortedDictionary sorts by keys.The OP wants to sort by value.SortedDictionary doesn't help in this case.

2019年03月24日40分46秒

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

2019年03月23日40分46秒

mbrownnyc - nope, doing that requires the assumption or precondition that the VALUES are unique, which is not guaranteed.

2019年03月24日40分46秒

Similar to 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).

2019年03月23日40分46秒

By putting the sorted items back into a dictionary, they are no longer guaranteed to be sorted when you enumerate the new dictionary.

2019年03月24日40分46秒

And why are you adding this answer when this is already answered?

2019年03月23日40分46秒

This answer is incorrect, as the resulting dictionary is not guaranteed to be ordered.

2019年03月24日40分46秒