在C#中,如何输出Dictionary类的内容?

时间:2012-08-23 01:36:53

标签: c# dictionary

在C#中,如何输出Dictionary类的内容?

使用键和值加载Dictionary类后,如何循环它们并在foreach循环中输出各个值?

6 个答案:

答案 0 :(得分:3)

以下是http://www.dotnetperls.com/dictionary

的示例
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    // Example Dictionary again
    Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };
    // Loop over pairs with foreach
    foreach (KeyValuePair<string, int> pair in d)
    {
        Console.WriteLine("{0}, {1}",
        pair.Key,
        pair.Value);
    }
    // Use var keyword to enumerate dictionary
    foreach (var pair in d)
    {
        Console.WriteLine("{0}, {1}",
        pair.Key,
        pair.Value);
    }
    }
}

最后一个循环使用 var 来声明KeyValuePair对象。这种方式更容易,因为您不必担心声明字典中使用的类型,并为CLR生成相同的结果。

答案 1 :(得分:3)

如果您只想输出它们,则不需要foreach循环 您可以使用LINQ ForEach

myDictionary.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));

答案 2 :(得分:2)

foreach (KeyValuePair<string, int> pair in myDictionary)
{
    Console.WriteLine("{0}, {1}",
    pair.Key,
    pair.Value);
}

答案 3 :(得分:1)

foreach(var key in pair.Keys){
   Console.WriteLine("{0} - {1}", key, pair[key]);      
}

答案 4 :(得分:1)

试试这个

Dictionary<object, object> dummyDictionary = new Dictionary<object, object>
            {
                {"India","Delhi"},
                {"USA","WashingtonDC"},
                {"Bangaladesh","Dhaka"},
                {"Pakistan","Karachi"}
            };

// Foreach循环构造

foreach (KeyValuePair<object, object> kvp in dummyDictionary)
{
  Console.WriteLine(string.Format("Key = {0}  Value = {1}", kvp.Key, kvp.Value));
}

//使用Linq和Foreach扩展方法

var result =
             (from kvp in dummyDictionary
              select new
              {
                Key = kvp.Key
                ,
                 Value = kvp.Value
              });
result.ToList().ForEach(kvp => Console.WriteLine(string.Format("Key = {0}  Value = {1}", kvp.Key, kvp.Value)));

Console.ReadKey();

答案 5 :(得分:0)

你是什么意思,说并输出个别值?您是否期望只看到独特的价值观?

        Dictionary<string, string> dict = new Dictionary<string, string>
        {
            {"1","one"},
            {"2","two"},
            {"3","three"},
            {"4","one"}
        };

        foreach (var value in dict.Values.Distinct())
        {
            Console.WriteLine(value);
        }
        Console.ReadLine();

也就是说,您可以使用Distinct()获取唯一值,而dict.Values是字典的ValueColection