0

I have a dictionary that has int keys. The keys are in random order and are not necesserily consequtive (e.g. 5, 3, 11, 12, 10, 4). I would like to visit each key-value pair in reverse order of key size. So for the example above I'd like to visit (12,11,10...).

The way I see how to do this is to get a count of the number of elements, find the max key by say binary search and then find the next largest value that is smaller than the current max etc. untill I've processed the number of elements contained in the dictionary.

However, there could be a method already existing. For a discussion on how to find the max key: Get the largest key in a dictionary

Community
  • 1
  • 1
s5s
  • 11,159
  • 21
  • 74
  • 121

4 Answers4

8
var pairs = dictionary.OrderByDescending(pair => pair.Key);
foreach(var pair in pairs)
{
    var value = pair.Value;
    ...
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 2
    `foreach(var pair in pairs)`* – Joseph Yaduvanshi Nov 29 '11 at 19:01
  • +1 for breaking it into separate statements. I don't like to inline LINQ statements. – jeremyalan Nov 29 '11 at 19:05
  • @JimSchubert, thanks! I had initially written a different solution and forgot to change that part... – Thomas Levesque Nov 29 '11 at 19:16
  • @jeremyalan (offtopic) Splitting LINQ out may look misleading, as it gives a false impression of ordering by key happening ahead of enumeration. In reality, ordering does not start until we hit foreach. If you add ToList/ToArray to the end of LINQ chain, then separating the two calls would make perfect sense. – Sergey Kalinichenko Nov 29 '11 at 19:16
2
foreach (var p in myDict.OrderByDescending(pair => pair.Key)) {
    // process pair
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Well, it's easy enough to retrieve all of the keys from a dictionary, you can then use the LINQ OrderByDescending() operator to get them in reverse order:

foreach( var key in yourDictionary.Keys.OrderByDescending(x => x) )
{
   // your logic here
}

If you need the value associated with the key, you can also do:

foreach( var keyValuePair in yourDictionary.OrderByDescending(kvp => kvp.Key) )
{
    // your logic here
}

You can, of course, use query comprehension syntax is LINQ as well:

var yourResult = from kvp in dictionary
                 order by kvp.Key descending
                 select YourProjectionFunction(kvp);
LBushkin
  • 129,300
  • 32
  • 216
  • 265
0
dic = dic.OrderByDescending(p=>p.Key).ToDictionary(p => p.Key, p => p.Value);
Reza ArabQaeni
  • 4,848
  • 27
  • 46