Red*_*wan 23 c# ordereddictionary
如何通过索引从OrderedDictionary获取项的键和值?
Mar*_*R-L 45
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
Run Code Online (Sandbox Code Playgroud)
没有直接的内置方法来做到这一点.这是因为OrderedDictionary索引是关键; 如果你想要实际的密钥,那么你需要自己跟踪它.可能最直接的方法是将密钥复制到可索引集合:
// dict is OrderedDictionary
object[] keys = new object[dict.Keys.Count];
dict.Keys.CopyTo(keys, 0);
for(int i = 0; i < dict.Keys.Count; i++) {
Console.WriteLine(
"Index = {0}, Key = {1}, Value = {2}",
i,
keys[i],
dict[i]
);
}
Run Code Online (Sandbox Code Playgroud)
您可以将此行为封装到一个包含访问权限的新类中OrderedDictionary.