在 C# 中使用 Hashtable 和 Dictionary

csharpprogrammingserver side programming更新于 2025/10/15 14:07:17

Hashtable

Hashtable 类表示基于键的哈希码组织的键值对的集合。它使用键来访问集合中的元素。

Hashtable 类中的一些常用方法包括 −

Sr.No.方法 &说明
1public virtual void Add(object key, object value);
将具有指定键和值的元素添加到 Hashtable 中。
2public virtual void Clear();
从 Hashtable 中删除所有元素。
3public virtual bool ContainsKey(object key);
确定 Hashtable 是否包含特定键。
4public 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# 中键和值的集合。字典 包含在 System.Collection.Generics 命名空间中。

以下是方法 −

Sr.No.方法 &说明
1Add
在字典中添加键值对
2Clear()
删除所有键和值
3Remove
删除具有指定键的元素。
4ContainsKey
检查指定的键是否存在于字典<TKey, TValue>中。
5ContainsValue
检查指定的键值是否存在于字典<TKey, TValue>。
6Count
计算键值对的数量。
7Clear
从字典 <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);
   }
}

相关文章