Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

hashtable in c#

/*
 * HashTable is a non generic collction which stores key,value pairs like Dictionary<TKey, TValue>
 * Under the System.Collection
 * Keys must be unique and cannot be null
 * Values can be null and suplicates
 * Values can be accessed by the keys
 * The key values are stored in the DixtionaryEntry objects
 * Kesy can be off different types
 */
//Lets create a HashTable
using System.Collections;
//Declaring a hashtable
Hashtable a1 = new Hashtable();
//Uisng var
var a3 = new Hashtable();
//Declaring initilising a hashtable
Hashtable a2 = new Hashtable() { { 1, "Subhasis" }, { "Name", "Biswal"}, { true, false} };
//Add the elements to the Hashtable
a2.Add(2, "Arun");
foreach (DictionaryEntry e in a2)
    Console.WriteLine($"The key and value pairs by foreach and dictionaryentry : {e.Key}, {e.Value}");
//using var : does not work here
/*foreach (var e in a2)
    Console.WriteLine($"The key and value by using var : {e.Key} {e.Value}");*/
/*The key and value pairs by foreach and dictionaryentry : Name, Biswal
The key and value pairs by foreach and dictionaryentry : 2, Arun
The key and value pairs by foreach and dictionaryentry : 1, Subhasis
The key and value pairs by foreach and dictionaryentry : True, False

*/
//Update the Hashtable: here these are the object so we have to use the unboxing methods to convert the object to data type
string name = (string)a2["Name"];
bool r = (bool)a2[true];

// Now update: you can update to any data types you want
a2["Name"] = "Suvalipsa";
a2[true] = "Hello";
foreach(DictionaryEntry en in a2)
    Console.WriteLine($"Keys and Values after updation : {en.Key}, {en.Value}");
/*Keys and Values after updation : Name, Suvalipsa
Keys and Values after updation : 2, Arun
Keys and Values after updation : 1, Subhasis
Keys and Values after updation : True, Hello*/
//Remove element from the hashtable : Remove()
a2.Remove(2);
a2.Remove(true);

//to get the keys and values separately you have to use the  var keyword insted of the DictionaryEntry
foreach (var f in a2.Keys)
    Console.WriteLine($"The keys are {f}");
foreach (var g in a2.Values)
    Console.WriteLine($"The values are {g}");
/*The keys are 1
The keys are Name
The values are Subhasis
The values are Suvalipsa*/


 
PREVIOUS NEXT
Tagged: #hashtable
ADD COMMENT
Topic
Name
9+5 =