简体   繁体   中英

What is the best way to iterate over a SortedDictionary backwards?

I need to loop through a dictionary.. backwards from the normal foreach.. loop. What is the best way to accomplish this?

Update

There is an external object that is returning SortedDictionary to me. The "string" must be unique, and reference a corresponding object myObject. I'd like to sort the list alphabetically by "string"... in reverse.

What other object would you recommend to serve this purpose?

Well the Dictionary<K,V> class uses a hash table internally to store its keys so there is no implied order. The order you added the keys is not preserved so there's really no meaningful way to "reverse" that.

But having said that, if you had an ordered collection such as a List or SortedDictionary , you could use the LINQ Reverse method to reverse any sequence.

Update

In response to your update about having a SortedDictionary, please refer to the Enumerable.Reverse method I linked to above. You can either reverse the dictionary (as a collection of KeyValuePair or its Keys property as a collection of strings).

SortedDictionary<string,object> dictionary = blah;
var keyValuePairs = dictionary.Reverse();
var keys = dictionary.Keys.Reverse();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM