【问题标题】:How do I print a Dictionary collection in C#?如何在 C# 中打印字典集合?
【发布时间】:2013-11-07 16:22:16
【问题描述】:

我正在尝试在这里打印出一个数组/集合。我有一个带有以下代码的类文件来打印出文本:

//Display All
    public void Display()
    {
        Console.WriteLine(ID + "\t" + Product + "\t" + Category + "\t" + Price + "\t" + Stock + "\t" + InBasket);
    }

然后,我主要尝试使用以下方法将其实际打印到屏幕上:

foreach (KeyValuePair<int, Farm_Shop> temp in products)
        {
            //display each product to console by using Display method in Farm Shop class
            temp.Display();
        }

但是我得到以下错误:

'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>' 
does not contain a definition for 'Display' and no extension method 'Display'
accepting a first argument of type 
'System.Collections.Generic.KeyValuePair<int,Farm_Shop_Assignment.Farm_Shop>' 
could be found (are you missing a using directive or an assembly reference?)

这是我要打印的实际内容:

products = new Dictionary<int, Farm_Shop>
        {
            { 1, new Farm_Shop(1, "Apple", "Fruit\t", 0.49, 40, 'n') },
            { 2, new Farm_Shop(2, "Orange", "Fruit\t", 0.59, 35, 'n') }
        };

据我了解,这不起作用,因为我只是发送要打印的数组/集合,而不是要打印的 int,如果您知道我的意思的话。

谁能告诉我如何才能让它正确打印。

非常感谢。谢谢。

【问题讨论】:

  • 在面向数据的类中使用这样的“显示”副作用方法是可疑的。考虑使用string ToString()string GetDisplayText { get; } 或类似的(并保持外部显示)。

标签: c# arrays collections dictionary generic-collections


【解决方案1】:

Display()Farm_Shop 上的一个方法。您不能直接在KeyValuePair&lt;int, Farm_Shop&gt; 类型的对象上调用它。您应该这样做以访问 key/value pair 中的 Farm_Shop 实例:

foreach (KeyValuePair<int, Farm_Shop> temp in products)
    {
        //display each product to console by using Display method in Farm Shop class
        temp.Value.Display();
    }

或者循环遍历Values 属性,因为密钥不会为您增加太多(因为它来自Farm_Shop 上的属性:

foreach (Farm_Shop temp in products.Values)
    {
        //display each product to console by using Display method in Farm Shop class
        temp.Display();
    }

【讨论】:

    【解决方案2】:

    这将遍历字典中的每个 KeyValue 对,并为您获取每个 jey 的值

    foreach (KeyValuePairtemp in products) //遍历字典 { Console.WriteLine(temp.Value); }

    【讨论】:

      【解决方案3】:

      应该是这样的

      foreach (var product in products)
      {
        product.Value.Display();
      }
      

      现在您可以通过这种方式使您的 Display 方法更易于理解:

      public Display()
      {
         var out=String.Format("{1}\t{2}\t{3}\t{4}\t{5}",_id,_productName,_categoryName,_this,_that [...]);
         Console.WriteLine(out);
      }
      

      【讨论】:

        【解决方案4】:

        您可以覆盖对象的 .ToString() 方法并调用它,而不是创建 Display 方法。然后在你的循环中你可以这样做:

        foreach(Farm_Shop item in products.Values)
        {
            Console.WriteLine(item.ToString());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-12
          • 2012-12-18
          • 1970-01-01
          • 2022-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多