在 C# 中使用 Hashtable 和 Dictionary
Hashtable
Hashtable 類表示鍵值對的集合,這些鍵值對根據鍵的雜湊碼進行組織。它使用鍵來訪問集合中的元素。
Hashtable 類中一些常用的方法如下:
序號 | 方法及描述 |
---|---|
1 | public virtual void Add(object key, object value); 向 Hashtable 中新增具有指定鍵和值的元素。 |
2 | public virtual void Clear(); 從 Hashtable 中移除所有元素。 |
3 | public virtual bool ContainsKey(object key); 確定 Hashtable 是否包含特定鍵。 |
4 | public virtual bool ContainsValue(object value); 確定 Hashtable 是否包含特定值。 |
以下是一個示例,展示了在 C# 中使用 Hashtable 類的用法:
示例
using System; using System.Collections; namespace Demo { class Program { static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add("D01", "Finance"); ht.Add("D02", "HR"); ht.Add("D03", "Operations"); if (ht.ContainsValue("Marketing")) { Console.WriteLine("This department name is already in the list"); } else { ht.Add("D04", "Marketing"); } ICollection key = ht.Keys; foreach (string k in key) { Console.WriteLine(k + ": " + ht[k]); } Console.ReadKey(); } } }
輸出
D04: Marketing D02: HR D03: Operations D01: Finance
Dictionary
Dictionary 是 C# 中鍵值對的集合。Dictionary <TKey, TValue> 包含在 System.Collection.Generics 名稱空間中。
以下是一些方法:
序號 | 方法及描述 |
---|---|
1 | Add 在 Dictionary 中新增鍵值對 |
2 | Clear() 移除所有鍵值對 |
3 | Remove 移除具有指定鍵的元素。 |
4 | ContainsKey 檢查 Dictionary <TKey, TValue> 中是否存在指定的鍵。 |
5 | ContainsValue 檢查 Dictionary <TKey, TValue> 中是否存在指定的鍵值。 |
6 | Count 計算鍵值對的數量。 |
7 | Clear 從 Dictionary <TKey, TValue> 中移除所有元素。 |
讓我們看看如何向 Dictionary 中新增元素並顯示計數:
示例
using System; using System.Collections.Generic; public class Demo { public static void Main() { IDictionary <int, int> d = new Dictionary <int, int> (); d.Add(1,44); d.Add(2,34); d.Add(3,66); d.Add(4,47); d.Add(5,76); Console.WriteLine(d.Count); } }
廣告