在 C# 中使用 Hashtable 和 Dictionary
csharpprogrammingserver side programming更新于 2025/10/15 14:07:17
Hashtable
Hashtable 类表示基于键的哈希码组织的键值对的集合。它使用键来访问集合中的元素。
Hashtable 类中的一些常用方法包括 −
| Sr.No. | 方法 &说明 |
|---|---|
| 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 是否包含特定值。 |
以下是 Hashtable 类用法的示例C# −
示例
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
字典
字典是 C# 中键和值的集合。字典
以下是方法 −
| Sr.No. | 方法 &说明 |
|---|---|
| 1 | Add 在字典中添加键值对 |
| 2 | Clear() 删除所有键和值 |
| 3 | Remove 删除具有指定键的元素。 |
| 4 | ContainsKey 检查指定的键是否存在于字典<TKey, TValue>中。 |
| 5 | ContainsValue 检查指定的键值是否存在于字典<TKey, TValue>。 |
| 6 | Count 计算键值对的数量。 |
| 7 | Clear 从字典 <TKey, TValue> 中删除所有元素。 |
让我们看看如何向字典中添加元素并显示计数 −
示例
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);
}
}

