我有一个声明的列表,如:
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语句不能对object类型的变量进行操作,因为object不包含GetEnumerator的公共定义。
如何通过指向myList
?
"DictionaryItem"
答案 0 :(得分:2)
foreach语句只能用于继承IEnumerable
的对象。由于您词典的TValue
为object
,因此您的foreach语句即使实际上是IEnumerable
也无法编译。
您可以通过多种方式解决该问题:
更改您的TValue
最好的选择,只有当你可以:
var myDictionary = new Dictionary<string, string[]>();
注意变量定义中的关键字var
。在实例化这样的对象时,可以节省大量时间。
将myDictionary["DictionaryItem"]
的结果投射到IEnumerable
如果词典中有其他类型的对象,则为危险选项。
foreach (string element in (myDictionary["DictionaryItem"] as string[]))
{
Console.WriteLine(element);
}
备注:我在谈论IEnumerable
,我在我的选项中使用string[]
。这是因为C#数组([]
)继承自IEnumerable
答案 1 :(得分:1)
在此示例中,您不确定为什么要将string[]
称为对象 - 您是否希望将object[]
用于数组?
无论哪种方式,错误都非常明确。
您需要使用Dictionary<string, string[]> myDictionary
答案 2 :(得分:1)
这只是一个对象,所以foreach不会知道它是如何处理的
string[] myList = (string[])myDictionary["DictionaryItem"];
foreach(string s in myList)
{
Console.WriteLine(element);
}
答案 3 :(得分: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);
}