1

I'd like to order a dictionary by the value. It seems the way it would usually be done in .Net doesn't exist in the Mono API.

Is there any particular API call or should I do this myself?

Thanks

Steve
  • 21,163
  • 21
  • 69
  • 92
  • 4
    What is "the way it would usually be done in .Net"? Can you provide an example, please? – O. R. Mapper Mar 05 '13 at 12:00
  • It seems that you haven't search the net yet. – Guy P Mar 05 '13 at 12:02
  • If it's a `System.Collections.Generic.Dictionary<,>`, then the dictionary in itself has no particular ordering, hence cannot be sorted. If you want an `IEnumerable<>` (sequence) with the key/value pairs of the dictionary such that the `IEnumerable<>` is sorted, use e.g. LINQ method `OrderBy`. – Jeppe Stig Nielsen Mar 05 '13 at 12:03
  • @O.R.Mapper - http://stackoverflow.com/questions/289/how-do-you-sort-a-c-sharp-dictionary-by-value .@Guy I did, nothing that worked in Mono came up. – Steve Mar 05 '13 at 13:00
  • 1
    @steve: And what about that does *not* work in Mono? The code provided in the accepted answer to that question compiles and runs for me with `mcs`/`gmcs` and `mono` without any compiler/runtime errors, respectively. (checked with Mono 2.10.9 on Win 7 x64) – O. R. Mapper Mar 05 '13 at 13:16
  • Hrm... our mono V must be out of date. It throws compilation error for me. Not sure which version of Mono we're using, just that its on linux (shouldnt matter I assume) – Steve Mar 05 '13 at 13:33
  • @steve: What is the error message? (Please make sure to write `@` and my user name in front of your replies, or else I won't be notified about your messages and will find them only by chance.) – O. R. Mapper Mar 05 '13 at 20:52
  • @steve: Also, you can determine the version of your Mono installation with `mono --version`. – O. R. Mapper Mar 05 '13 at 21:37

2 Answers2

2

As commented, the Dictionary class has no ordering. If you want a Dictionary that is ordered, there is the SortedDictionary class.

But the SortedDictionary is ordered by it's keys. Keeping an ordering dictionary by it's values doesn't seem an usual task.

Anyway, if you want to access the values sorted you could do:

dict.Values.OrderBy(v => v).ToList(); //Sorted list of the values of the dictionary dict

or

dict.OrderBy(kvp => kvp.Value).ToList(); //Sorted list (by value) of the key value pairs of the dictionary dict
talles
  • 14,356
  • 8
  • 45
  • 58
0

you can use Linq:

var dict = new Dictionary<string, int>();
var sorted = dict.OrderBy(kvp => kvp.Value).ToList();
Dave Bish
  • 19,263
  • 7
  • 46
  • 63