Add elements to a Hashtable
In this chapter you will learn:
Adding to Hashtable
The following code uses
Add
method to add elements to the Hashtable
and uses the Keys
to obtain the values.
using System; /*j a v a 2 s . c om*/
using System.Collections;
class HashtableDemo {
public static void Main() {
Hashtable ht = new Hashtable();
ht.Add("a", "A");
ht.Add("b", "B");
ht.Add("c", "C");
ht.Add("e", "E");
// Get a collection of the keys.
ICollection c = ht.Keys;
foreach(string str in c)
Console.WriteLine(str + ": " + ht[str]);
}
}
The code above generates the following result.
Adding with indexer
Other than using Add
method to add key and value pair to
a Hashtable
we can also add
key-value pair to Hashtable
by using the indexer.
using System; /* j a v a 2 s. c om*/
using System.Collections;
class HashtableDemo {
public static void Main() {
Hashtable ht = new Hashtable();
ht.Add("a", "A");
ht.Add("b", "B");
ht.Add("c", "C");
ht.Add("e", "E");
ht["f"] = "F";
// Get a collection of the keys.
ICollection c = ht.Keys;
foreach(string str in c)
Console.WriteLine(str + ": " + ht[str]);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Collections