【问题标题】:How to print contents of a list via a dictionary?如何通过字典打印列表的内容?
【发布时间】:2017-12-27 17:15:00
【问题描述】:

我有一个声明如下的列表:

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 的公共定义。

如何通过指向"DictionaryItem" 的值来打印myList?

【问题讨论】:

  • 将 myDictionary["DictionaryItem"] 转换为数组或您需要的任何内容。
  • 除非有严格的要求,最好尽可能尝试使用强类型对象,例如:Dictionary&lt;string, string[]&gt; 或 Dictionary&lt;string, IEnumerable&lt;string&gt; 等,在您的情况下,以减少不必要且昂贵的 Casts,您可以获得在受支持的 IDE 中提供智能感知支持。

标签: c# list dictionary foreach


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不知道为什么您在此示例中将 string[] 称为对象 - 您是否希望将 object[] 用于数组? 无论哪种方式,错误都非常明确。 您需要使用Dictionary&lt;string, string[]&gt; myDictionary

    【讨论】:

      【解决方案3】:

      它只是一个对象,所以 foreach 不会知道如何处理它

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

      【讨论】:

        【解决方案4】:

        您可以从 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);
                }
        

        【讨论】:

          猜你喜欢
          • 2016-10-10
          • 1970-01-01
          • 1970-01-01
          • 2017-08-20
          • 1970-01-01
          • 1970-01-01
          • 2021-07-15
          • 2022-01-04
          • 2015-10-03
          相关资源
          最近更新 更多