簡體   English   中英

在C#中,如何輸出Dictionary類的內容?

[英]In C#, how do you output the contents of a Dictionary class?

在C#中,如何輸出Dictionary類的內容?

將鍵和值加載到Dictionary類后,如何在它們之間循環並在foreach循環中輸出各個值?

這是來自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對象。 這樣就更容易了,因為您不必擔心聲明在Dictionary中使用的類型,並且可以向CLR產生相同的結果。

如果只想輸出它們,則不需要foreach循環。
您可以使用LINQ ForEach

myDictionary.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value));
foreach (KeyValuePair<string, int> pair in myDictionary)
{
    Console.WriteLine("{0}, {1}",
    pair.Key,
    pair.Value);
}
foreach(var key in pair.Keys){
   Console.WriteLine("{0} - {1}", key, pair[key]);      
}

嘗試這個

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();

您說的是什么,說出並輸出各個值 您是否只希望看到唯一的值?

        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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM