2017-07-21 49 views
1

我有一個列表中聲明,如:如何通過字典打印列表的內容?

string[] myList = { "Item One", "Item Two", "Item Three" }; 

並與一個元素,一個詞典這對上面所列內容價值點:

Dictionary<string, object> myDictionary = new Dictionary<string, object>(); 
myDictionary.Add("DictionaryItem", myList); 

我想通過指向要打印的myList內容字典中的值。我曾嘗試:

foreach (string element in myDictionary["DictionaryItem"]) 
{ 
    Console.WriteLine(element); 
} 

返回語法錯誤:

foreach statement cannot operate on variables of type object because object does not contain a public definition for GetEnumerator.

如何打印myList,所指向的"DictionaryItem"價值?

+0

可能重複[什麼是在C#中迭代字典的最佳方式?](https://stackoverflow.com/questions/141088/what-is-the-最好的方式迭代在字典中的c) – garfbradaz

+0

鑄造myDictionary [「DictionaryItem」]到一個數組或你需要什麼。 –

+1

除非有嚴格的要求,否則理想情況下儘量使用強類型對象,例如'Dictionary '或'Dictionary '等等,以減少不必要和昂貴的強制轉換,您可以在受支持的IDE中獲得智能感知支持作爲獎勵。 –

回答

1

不知道你爲什麼在本例中將string[]作爲對象 - 你是否想用object[]作爲數組? 無論哪種方式,錯誤是非常明確的。 您將需要使用Dictionary<string, string[]> myDictionary

2

foreach語句只能用於繼承IEnumerable的對象。由於您的字典中的TValueobject,因此您的foreach語句無法編譯,即使它實際上是IEnumerable

您有幾種選擇來解決這一問題:

更改TValue

最好的選擇,只要你當然可以:

var myDictionary = new Dictionary<string, string[]>(); 

通知變量中的keywork var定義。當像這樣實例化對象時,您可以節省大量時間。

演員的myDictionary["DictionaryItem"]結果爲IEnumerable

危險的選擇,如果有其他類型的對象在你的字典。

foreach (string element in (myDictionary["DictionaryItem"] as string[])) 
{ 
    Console.WriteLine(element); 
} 

注:我說的是IEnumerable,我使用我的選擇string[]。這是因爲C#陣列([])從IEnumerable

1

繼承它僅僅是一個對象,這樣的foreach是不會知道如何處理它

string[] myList = (string[])myDictionary["DictionaryItem"]; 

foreach(string s in myList) 
{ 
    Console.WriteLine(element); 
} 
0

你可以從你創建的字符串列表中的String []和重複這一點。請注意,您要迭代字典項目的值。

 string[] myList = { "Item One", "Item Two", "Item Three" }; 
     Dictionary<string, object> myDictionary = new Dictionary<string, object>(); 
     myDictionary.Add("DictionaryItem", myList); 


     //Short Hand 
     foreach (var item in new List<string>((string[])myDictionary.First(m => m.Key == "DictionaryItem").Value)) 
     { 
      Console.WriteLine(item); 
     } 

     //or Long Hand version 
     KeyValuePair<string, object> element = myDictionary.First(m => m.Key == "DictionaryItem"); 
     List<String> listItem = new List<string>((string[])element.Value); 
     foreach (var item in listItem) 
     { 
      Console.WriteLine(item); 
     }