📜  C#|将元素添加到哈希表中

📅  最后修改于: 2021-05-29 17:27:44             🧑  作者: Mango

Hashtable类表示键和值对的集合,这些键和值对是根据键的哈希码进行组织的。该键用于访问集合中的项目。 Hashtable.Add(Object,Object)方法用于将具有指定键和值的元素添加到Hashtable中。

句法:

public virtual void Add(object key, object value);

参数:

例外情况:

  • ArgumentNullException :如果null
  • ArgumentException :如果哈希表中已经存在具有相同键的元素。
  • NotSupportedException :Hashtable是只读的,或者Hashtable具有固定的大小。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code for adding an element with the
// specified key and value into the Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("g", "geeks");
        myTable.Add("c", "c++");
        myTable.Add("d", "data structures");
        myTable.Add("q", "quiz");
  
        // Get a collection of the keys.
        ICollection c = myTable.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
    }
}
输出:
d: data structures
c: c++
q: quiz
g: geeks

范例2:

// C# code for adding an element with the
// specified key and value into the Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("4", "Even");
        myTable.Add("9", "Odd");
        myTable.Add("5", "Odd and Prime");
        myTable.Add("2", "Even and Prime");
  
        // Get a collection of the keys.
        ICollection c = myTable.Keys;
  
        // Displaying the contents
        foreach(string str in c)
            Console.WriteLine(str + ": " + myTable[str]);
    }
}
输出:
5: Odd and Prime
9: Odd
2: Even and Prime
4: Even

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.add?view=netframework-4.7.2