【发布时间】:2017-06-02 17:05:43
【问题描述】:
如何反向遍历 OrderedDictionary 并访问其密钥?
由于它不支持 LINQ 扩展,我尝试了以下方法:
var orderedDictionary= new OrderedDictionary();
orderedDictionary.Add("something", someObject);
orderedDictionary.Add("another", anotherObject);
for (var dictIndex = orderedDictionary.Count - 1; dictIndex != 0; dictIndex--)
{
// It gives me the value, but how do I get the key?
// E.g., "something" and "another".
var key = orderedDictionary[dictIndex];
}
【问题讨论】:
-
以反向或正常顺序迭代它并不重要,因为正如文档所述,OrderedDictionary 的元素不按键排序,这与 SortedDictionary
类。 -
插入顺序是我使用 OrderDictionary 的原因,我需要相应地迭代它(反向)。
-
你总是可以遍历字典的keys属性。
-
@jdweng 但我需要根据插入顺序反向迭代字典。在该迭代期间,我需要选择键来执行其他操作。
-
我明白了。不幸的是,这个类被过度封装了。索引器的implementation 是这样的
return ((DictionaryEntry)objectsArray[index]).Value;,你需要这样的方法return ((DictionaryEntry)objectsArray[index]);不存在。
标签: c# linq ordereddictionary