简体   繁体   English

向后迭代SortedDictionary的最佳方法是什么?

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

I need to loop through a dictionary.. backwards from the normal foreach.. loop. 我需要从普通的foreach..循环foreach..字典.. What is the best way to accomplish this? 做到这一点的最佳方法是什么?

Update 更新资料

There is an external object that is returning SortedDictionary to me. 有一个外部对象正在向我返回SortedDictionary。 The "string" must be unique, and reference a corresponding object myObject. “字符串”必须唯一,并引用相应的对象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. 好的Dictionary<K,V>类在内部使用哈希表来存储其键,因此没有隐含的顺序。 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. 话虽如此,如果您有一个有序的集合(例如List或SortedDictionary) ,则可以使用LINQ Reverse方法来反转任何序列。

Update 更新资料

In response to your update about having a SortedDictionary, please refer to the Enumerable.Reverse method I linked to above. 为了响应您关于拥有SortedDictionary的更新,请参考我上面链接的Enumerable.Reverse方法。 You can either reverse the dictionary (as a collection of KeyValuePair or its Keys property as a collection of strings). 您可以反转字典(作为KeyValuePair的集合,或者将其Keys属性作为字符串的集合)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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