TAGS :Viewed: 9 - Published at: a few seconds ago

[ C# iterate keys in reverse order ]

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: C# Get largest key in dictionary

Answer 1


var pairs = dictionary.OrderByDescending(pair => pair.Key);
foreach(var pair in pairs)
{
    var value = pair.Value;
    ...
}

Answer 2


foreach (var p in myDict.OrderByDescending(pair => pair.Key)) {
    // process pair
}

Answer 3


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

Answer 4


dic = dic.OrderByDescending(p=>p.Key).ToDictionary(p => p.Key, p => p.Value);