0

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

一旦你加载了一个带有键和值的 Dictionary 类,我如何循环它们并在 foreach 循环中输出各个值?

4

6 回答 6

3

If you just want to output them you dont need a foreach loop.
You can use LINQ ForEach:

myDictionary.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));
于 2012-08-23T02:03:16.603 回答
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 生成相同的结果。

于 2012-08-23T01:39:53.833 回答
2
foreach (KeyValuePair<string, int> pair in myDictionary)
{
    Console.WriteLine("{0}, {1}",
    pair.Key,
    pair.Value);
}
于 2012-08-23T01:39:39.190 回答
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();
于 2012-08-23T03:18:54.270 回答
1
foreach(var key in pair.Keys){
   Console.WriteLine("{0} - {1}", key, pair[key]);      
}
于 2012-08-23T01:41:09.253 回答
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

于 2012-08-23T02:09:36.440 回答