some of the commonly used methods in hashtable class are −
sr.no.method & description
1 public virtual void add(object key, object value);adds an element with the specified key and value into the hashtable.
2 public virtual void clear();removes all elements from the hashtable.
3 public virtual bool containskey(object key);determines whether the hashtable contains a specific key.
4 public virtual bool containsvalue(object value);determines whether the hashtable contains a specific value.
the following is an example showing the usage of hashtable class in c# −
example live demo
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: hrd03: operationsd01: finance
字典字典是c#中的键值对集合。dictionary<tkey, tvalue>包含在system.collection.generics命名空间中。
以下是一些方法:
序号方法及描述
1 add
在字典中添加键值对
2 clear()
移除所有的键和值
3 remove
移除指定键的元素
4 containskey
检查字典中是否存在指定的键
5 containsvalue
检查字典中是否存在指定的键值
6 count
计算键值对的数量
7 clear
从字典中移除所有元素
让我们看看如何向字典中添加元素并显示数量:
示例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# 中使用哈希表和字典的详细内容。