C#|在哈希表中添加一个元素

Hashtable类表示 键和值对 根据密钥的哈希代码进行组织。密钥用于访问集合中的项目。 哈希表。添加(对象,对象)方法 用于将具有指定键和值的元素添加到哈希表中。

null

语法:

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

参数:

关键: 它是要添加类型为的元素的指定键 系统对象 .

价值: 它是要添加类型为的元素的指定值 系统对象 这个 价值 可以是 无效的 .

例外情况:

  • 无理例外 :如果 钥匙 无效的 .
  • 辩论例外 :如果元素具有相同的 钥匙 已存在于哈希表中。
  • 冒号 :哈希表为只读或哈希表大小固定。

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

例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

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享