如何通过索引从C#中的OrderedDictionary获取密钥?

Red*_*wan 23 c# ordereddictionary

如何通过索引从OrderedDictionary获取项的键和值?

Mar*_*R-L 45

orderedDictionary.Cast<DictionaryEntry>().ElementAt(index);
Run Code Online (Sandbox Code Playgroud)

  • `orderedDictionary.Cast<DictionaryEntry>().ElementAt(index).Key.ToString();` (6认同)
  • + 1这应该是实际接受的答案.在此验证 - https://referencesource.microsoft.com/#System/compmod/system/collections/specialized/ordereddictionary.cs,210 (3认同)
  • 使用`using System.Linq;` (2认同)

jas*_*son 8

没有直接的内置方法来做到这一点.这是因为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.

  • 索引肯定是*不是键 - 它们必然是``OrderedDictionary``中不同的结构. (3认同)
  • 被否决是因为索引不是关键,正如 @martin-rl 的答案所示 (2认同)