2017-07-21 96 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); 
     }