标签云

微信群

扫码加入我们

WeChat QR Code


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

2018年10月21日10分33秒

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.

2018年10月22日10分33秒

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!

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月21日10分33秒

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.

2018年10月21日10分33秒

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.

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

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月22日10分33秒

theJerm: not true

2018年10月21日10分33秒

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

2018年10月21日10分33秒

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.

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒

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.

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

Incorrect: stackoverflow.com/a/4007787/1860652

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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.

2018年10月22日10分33秒

stringnextPair -> string> nextPair stringfirstPair -> string> firstPair

2018年10月21日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒

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)

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒

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

2018年10月21日10分33秒

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

2018年10月22日10分33秒