2010-02-09 55 views

回答

10

没有直接内置的方式做到这一点。这是因为一个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一个新的类。

+1

我也一样,但再次看到: OrderedDictionary列表=的OrderItems; object strKey = list [e.OldIndex]; DictionaryEntry dicEntry = new DictionaryEntry(); foreach(DictionaryEntry DE in list) if(DE.Value == strKey) { dicEntry.Key = DE.Key; dicEntry.Value = DE.Value; }} – 2010-02-10 04:47:16

+0

@RedSwan:在哪里指数? – testing 2014-09-12 10:10:03

+2

该索引绝对*不是键 - 这些在OrderedDictionary中必然是不同的结构。 – Conrad 2015-02-26 19:14:23

35
orderedDictionary.Cast<DictionaryEntry>().ElementAt(index); 
+1

你先生的回答应该得到更多upvotes – Seb 2014-09-10 15:12:47

+1

使用'使用System.Linq的;' – testing 2014-09-12 09:56:54

+0

有了这个代码,你得到的元素。但是,如何在SO问题中获得关键和价值? – testing 2014-09-12 10:02:20

1

我创建了一些扩展方法,它们使用前面提到的代码通过索引和键值获取。

public static T GetKey<T>(this OrderedDictionary dictionary, int index) 
{ 
    if (dictionary == null) 
    { 
     return default(T); 
    } 

    try 
    { 
     return (T)dictionary.Cast<DictionaryEntry>().ElementAt(index).Key; 
    } 
    catch (Exception) 
    { 
     return default(T); 
    } 
} 

public static U GetValue<T, U>(this OrderedDictionary dictionary, T key) 
{ 
    if (dictionary == null) 
    { 
     return default(U); 
    } 

    try 
    { 
     return (U)dictionary.Cast<DictionaryEntry>().AsQueryable().Single(kvp => ((T)kvp.Key).Equals(key)).Value; 
    } 
    catch (Exception) 
    { 
     return default(U); 
    } 
} 
+0

如果你的目的是要恢复默认值,如果目标指数/关键不在词典中,你选择了一个昂贵的方式做到这一点。相对于像if/else这样的正常控制流构造,异常是非常昂贵的。最好是自己检查越界指数和不存在的密钥,而不是依赖发生的异常。 – Odrade 2015-07-02 21:15:15

相关问题