在C#中使用哈希表和字典
哈希表
Hashtable类表示键和值对的集合,这些键和值对基于键的哈希码进行组织。它使用键来访问集合中的元素。
Hashtable类中的一些常用方法是-
序号 | 方法与说明 |
---|---|
1 | public virtual void 将具有指定键和值的元素添加到哈希表中。 |
2 | public virtual void 从哈希表中删除所有元素。 |
3 | public virtual bool 确定哈希表是否包含特定键。 |
4 | public virtual bool 确定哈希表是否包含特定值。 |
以下示例显示了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: MarketingD02: HR
D03: Operations
D01: Finance
字典
字典是C#中键和值的集合。字典<TKey,TValue>包含在System.Collection.Generics命名空间中。
以下是方法-
序号 | 方法与说明 |
---|---|
1 | Add 在字典中添加添加键/值对 |
2 | Clear() 删除所有的键和值 |
3 | Remove 删除具有指定键的元素。 |
4 | ContainsKey 检查指定的键在Dictionary <TKey,TValue>中是否存在。 |
5 | ContainsValue 检查指定的键值在Dictionary <TKey,TValue>中是否存在。 |
6 | Count 计算键值对的数量。 |
7 | Clear 从 Dictionary <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);
}
}
以上是 在C#中使用哈希表和字典 的全部内容, 来源链接: utcz.com/z/340736.html