2013-05-25 19 views
1

這裏是我的代碼不能鍵入「字符串」轉換爲「System.Collections.ArrayList

private static ArrayList GetFirstObjectFromDictionary(Dictionary<string, string> dictionary) 
    { 
     foreach (ArrayList arr in dictionary.Values) //error 
     { 
      return arr; 
     } 
     return null; 
    } 

它會導致錯誤‘無法轉換類型‘字符串’到‘System.Collections.ArrayList’’。

+1

Your ** dictionary.Values **的類型是** Dictionary .ValueCollection **。所以你不能直接拋出它ArrayList和這個代碼看起來沒有意義!你能解釋一下你想做什麼嗎? –

+0

@Furkan Ekinci - 其實我想把字典中的每一項都放到ArrayList中的對象類型中,在實現Dictionary之前,我已經使用了hashtable來完成同一段代碼,由於性能原因,我已經將數據結構更改爲Dictionary。 – user2067120

回答

1

您可以使用KeyValuePair接觸字典的項目。

private static ArrayList GetFirstObjectFromHashTable(Dictionary<string, string> dictionary) 
{ 
    ArrayList aLst = new ArrayList(); 

    foreach (KeyValuePair<string, string> pair in dictionary) 
    { 
     aLst.Add(pair.Value); 
    } 

    return aLst; 
} 

This page可能會幫助您瞭解使用字典的foreach。

相關問題