在 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);
}
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP