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

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

没有直接的内置方法来做到这一点。 这是因为对于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] ); } 

您可以将此行为封装到一个新的类中,该类包含对OrderedDictionary访问。

 orderedDictionary.Cast().ElementAt(index); 

我创建了一些扩展方法,使用索引获取密钥,使用前面提到的代码按键获取值。

 public static T GetKey(this OrderedDictionary dictionary, int index) { if (dictionary == null) { return default(T); } try { return (T)dictionary.Cast().ElementAt(index).Key; } catch (Exception) { return default(T); } } public static U GetValue(this OrderedDictionary dictionary, T key) { if (dictionary == null) { return default(U); } try { return (U)dictionary.Cast().AsQueryable().Single(kvp => ((T)kvp.Key).Equals(key)).Value; } catch (Exception) { return default(U); } }