C#基础之哈希表(HashTable)

作者:微信公众号:【架构师老卢】
5-6 18:32
60

THashTable 与 System.Collections 命名空间有关。HashTable 包含键值对。其中每个键都与一个唯一值相关联。

带有示例的 C# 哈希表

C# 中哈希表的功能:

创建 HashTable:

您将使用 System.Collections 命名空间创建哈希表。下面的代码是创建哈希表的语法。

using System.Collections;  
Hashtable fruittable = new Hashtable();

添加键值对:

HashTable 包含键值对,要创建键值对,可以使用 Add 方法。在 Add 方法中,键在每个键值对中必须是唯一的。

fruittable.Add("FruitName", "Apple");  
fruittable.Add("FruitPrice", 20);  
fruittable.Add("FruitColor", "Red");

访问值:

您可以按其关联的键检索值:

string fruitname = (string)fruittable["FruitName"];  
int fruitprice = (int)fruittable["FruitPrice"];  
string fruitcolor = (string)fruittable["FruitColor"];

删除键值对:

您可以通过键-值对的键删除它们:

fruittable.Remove("FruitPrice");

检查是否存在:

可以使用 Contains 方法检查 HashTable 中是否存在键:

bool containsPrice = fruittable.Contains("FruitPrice"); // Returns false after removing "FruitPrice";

遍历 HashTable:

可以使用 DictionaryEntry 结构循环访问键值对:

foreach (DictionaryEntry entry in fruittable)  
{  
  Console.WriteLine($"{entry.Key}: {entry.Value}");  
}

其他 HashTable 操作:

HashTable 类还提供用于检查键值对数、清除 HashTable 等的方法和属性。

int count = hashtable.Count;  
hashtable.Clear(); // Removes all key-value pairs

C# 中的 HashTable with Example

using System;  
using System.Collections;  
public class Program  
{  
  public static void Main(string[] args)  
  {  
    Hashtable fruittable = new Hashtable();  
    fruittable.Add("FruitName", "Apple");  
    fruittable.Add("FruitPrice", 20);  
    fruittable.Add("FruitColor", "Red");  
    foreach (DictionaryEntry entry in fruittable)  
    {  
      Console.WriteLine($"{entry.Key}: {entry.Value}");  
    }  
    fruittable.Remove("FruitPrice");  
    foreach (DictionaryEntry entry in fruittable)  
    {  
      Console.WriteLine($"{entry.Key}: {entry.Value}");  
    }  
  }  
}

输出

FruitName: Apple  
FruitPrice: 20  
FruitColor: Red  
FruitName: Apple  
FruitColor: Red

HashTable 是键值对的集合。在键值对中,每个键必须是唯一的。HashTable 可以存储任何类型的数据(int、float、string、bool)。

相关留言评论
昵称:
邮箱:
阅读排行