Lesson #21 - Working with collections(Hashtable)

The hashtable collection is used to handle scenarios of Key-and-value pairs that should be organized based on the hash code of the key (The key is used to access the elements in the collection). This collection is mainly used in the case that we need to access elements by using a key that is simple to identify.


The following table lists some of the commonly used properties of the hashtable class:


class Program

{

static void Main(string[] args)

{

Hashtable WorkingWithHashtable = new Hashtable();

WorkingWithHashtable.Add("Hashtableindex_1","Value_1");

WorkingWithHashtable.Add("Hashtableindex_2", "Value_2");

WorkingWithHashtable.Add("Hashtableindex_3", "Value_3");

WorkingWithHashtable.Add("Hashtableindex_4", "Value_4");


Console.WriteLine("Is collection is IsReadOnly? " + WorkingWithHashtable.IsReadOnly);

Console.WriteLine("Is collection is IsFixedSize? " + WorkingWithHashtable.IsFixedSize);

Console.WriteLine("The number of Key values pairs: " + WorkingWithHashtable.Count);


ICollection CollectionKeys = WorkingWithHashtable.Keys;

ICollection CollectionValues = WorkingWithHashtable.Values;

//List of Keys and thier values

foreach (var listofkeys in CollectionKeys)

{

Console.WriteLine(listofkeys + " " + WorkingWithHashtable[listofkeys]);

}

}

}

Result:

Is collection is IsReadOnly? False

Is collection is IsFixedSize? False

The number of Key values pairs: 4

Hashtableindex_3 Value_3

Hashtableindex_1 Value_1

Hashtableindex_4 Value_4

Hashtableindex_2 Value_2

Press any key to continue . . .


The following table lists some of the commonly used methods of the hashtable class:

static void Main(string[] args)

{

Hashtable WorkingWithHashtable = new Hashtable();

//Add elements

WorkingWithHashtable.Add("Hashtableindex_1","Value_1");

WorkingWithHashtable.Add("Hashtableindex_2", "Value_2");

WorkingWithHashtable.Add("Hashtableindex_3", "Value_3");


//Remove elements by a specific key

WorkingWithHashtable.Remove("Hashtableindex_2");


//Contains Key

Console.WriteLine(WorkingWithHashtable.ContainsKey("Hashtableindex_3"));//Returns True


//Contains Value

Console.WriteLine(WorkingWithHashtable.ContainsValue("Value_4"));//Returns False


//Clear all elements

WorkingWithHashtable.Clear();

}



2 views0 comments