C# 中的 Dictionary 類


C# 中的字典是一個鍵和值集合。它是在 System.Collection.Generics 名稱空間中的泛型集合類。

語法

以下為語法 −

public class Dictionary<TKey,TValue>

上述型別中,key 引數是字典中鍵的型別,而 TValue 是值型別。

示例

現在,讓我們建立一個字典並新增一些元素 −

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
   }
}

輸出

這將生成以下輸出 −

Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan

示例

現在,讓我們看一個示例並刪除一些鍵 −

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("Removing some keys...");
      dict.Remove("Four");
      dict.Remove("Five");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.WriteLine("
Key/value pairs...");       foreach(KeyValuePair<string, string> res in dict){          Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);       }       Console.Write("
All the keys..
");       Dictionary<string, string>.KeyCollection allKeys = dict.Keys;       foreach(string str in allKeys){          Console.WriteLine("Key = {0}", str);       }    } }

輸出

這將生成以下輸出 −

Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three

更新於: 2019 年 11 月 6 日

654 次檢視

開始你的 職業發展

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.