C# Collections are The Specialized Classes to Store & Modify Data. In this Tutorial You will Learn About C# Collections Such as ArrayList, HashTable & SortedList With Examples:
They serve different purposes like dynamic memory allocation, assessing non-sequential data, etc.
All these classes use the object class which is the base class for all other data types.
=> Watch Out The Full C# Training Series Here
Table of Contents:
C# Collections And Their Usage
C# ArrayList
ArrayList is a part of collections in C#. It is used to contain data of any given data type. It is similar to an array in C# but it doesn’t have a definite size. Its size increases automatically as more elements are added in it.
How To Initialize An ArrayList?
ArrayList can be initialized by using the “ArrayList” keyword.
ArrayList arrList = new ArrayList();
How To Add Elements Into An ArrayList?
You can add a single item into an array list by using the Add() method and a range of elements or multiple elements from another collection by using the AddRange() method.
Example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7896); arrList.Add("Seven"); Console.ReadLine(); } } }
Here, you can see that we have used ArrayList.Add() method. As you can notice, we have added both integers as well as string in the same array list. This is possible as an array list is of non-generic data type, i.e. it can contain an element of any given data type.
How To Access An Element From An ArrayList?
An array list element can be accessed similar to an array i.e. by using the index. But as it’s a non-generic type, we first need to cast it to a suitable data type or need to use var keyword while accessing a value from the Array List.
Example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7896); arrList.Add("Seven"); //casted and retrieved data int first_index = (int)arrList[0]; string second_index = (string)arrList[1]; Console.WriteLine("The first index value is : " + first_index); Console.WriteLine("The second index value is : " + second_index); Console.ReadLine(); } } }
In the above example, we have retrieved the data by using the index of the array list and then we have cast it to the appropriate data type. The results have then been printed to the console as output.
The output for the above program will be:
Output
The first index value is: 7896
The second index value is: Seven
How To Insert An Element Into ArrayList?
To insert an element in the ArrayList at a specified point or index. the Insert() method is used.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7896); arrList.Add("Seven"); //casted and retrieved data int first_index = (int)arrList[0]; string second_index = (string)arrList[1]; Console.WriteLine("The first index value is : " + first_index); Console.WriteLine("The second index value is : " + second_index); arrList.Insert(1, "Eight"); second_index = (string)arrList[1]; Console.WriteLine("The second index value is : " + second_index); Console.ReadLine(); } } }
Thus, we have inserted a new string at index 1 using the insert() method. So, if we run the above program we will get the following output:
Output
The first index value is: 7896
The second index value is: Seven
The second index value is: Eight
How To Remove An Element From ArrayList?
An element can be removed from the ArrayList using the Remove() method. Remove method accepts a parameter i.e. the value that needs to be removed from the array.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7896); arrList.Add("Seven"); //casted and retrieved data int first_index = (int)arrList[0]; string second_index = (string)arrList[1]; Console.WriteLine("The first index value is : " + first_index); Console.WriteLine("The second index value is : " + second_index); arrList.Insert(1, "Eight"); second_index = (string)arrList[1]; Console.WriteLine("The second index value is : " + second_index); arrList.Remove(7896); var data = arrList[0]; Console.WriteLine("The value at 0 index is : " + data); Console.ReadLine(); } } }
The remove method removes the given value from the list. When the value is removed from the given index, the subsequent value moves one index upward to fill the gap. As we are removing 0 indexes, the value from index 1 will move and fill the void at 0.
The output of the following program will be:
Output
The first index value is: 7896
The second index value is: Seven
The second index value is: Eight
The value at 0 index is: Eight
How To Remove List Element Using The Index?
The user can remove a list element from a particular index by using the RemoveAt() method. RemoveAt() accepts a single parameter with an index number from which the element has to be removed. Similar to the Remove method, removing an element from the middle will push the next element to move one step upward to fill the gap.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7896); arrList.Add("Seven"); //casted and retrieved data int first_index = (int)arrList[0]; string second_index = (string)arrList[1]; Console.WriteLine("The first index value is : " + first_index); Console.WriteLine("The second index value is : " + second_index); arrList.Insert(1, "Eight"); second_index = (string)arrList[1]; Console.WriteLine("The second index value is : " + second_index); arrList.RemoveAt(1); var data = arrList[1]; Console.WriteLine("The value at 1 index is : " + data); Console.ReadLine(); } } }
In the above example, we have used, RemoveAt to remove index 1. Hence, the element at index 2 should move to index 1 to replace the gap.
The output of the following program will be:
Output
The first index value is : 7896
The second index value is : Seven
The second index value is : Eight
The value at 1 index is : Seven
How To Sort And Reverse An ArrayList?
ArrayList offers two different methods for sorting and reverse operations. There is only one condition i.e. all the elements inside the array list should have the same data type for comparison with a comparator or else it will throw a runtime error.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { ArrayList arrList = new ArrayList(); arrList.Add(7); arrList.Add(4); arrList.Add(5); arrList.Add(1); arrList.Add(3); Console.WriteLine("Original Array List"); foreach (var v in arrList) { Console.Write(v + " "); } //sorting an array list Console.WriteLine(); Console.WriteLine("Sorted Array List"); arrList.Sort(); foreach (var srt in arrList) { Console.Write(srt + " "); } //Reversing an array list Console.WriteLine(); Console.WriteLine("Reversed Array List"); arrList.Reverse(); foreach (var rvrs in arrList) { Console.Write(rvrs + " "); } Console.ReadLine(); } } }
In the above program, we have first created an array list with integer data type and then we have used the sort method to sort the list and the reverse method to reverse the sorted list.
So, the output of the following list will be:
Output
Original Array List
7 4 5 1 3
Sorted Array List
1 3 4 5 7
Reversed Array List
7 5 4 3 1
C# HashTable
System.Collections namespace in C# contains Hashtable that is quite similar to the Dictionary. Hashtable stores data in the form of key-value pairs.
It does that internally by assigning a hash code to hash key internally and whenever data is accessed it matches the hash code with a hash key to retrieve data. Each item in the table will have a key-value pair
How To Initialize A HashTable?
A HashTable can be initialized by using the keyword HashTable and then creating an instance of it.
Hashtable hashtbl = new Hashtable();
How To Add Elements To A HashTable?
Elements can be added to the HashTable using the method Add(). It allows the users to add an item with its key and value. It is not important to describe the data type of the key or value. While adding elements to the HashTable, you should remember that the keys cannot contain null whose values can be null.
HashTable.Add(Keys, Values);
Example:
class Program { static void Main(string[] args) { Hashtable hashtbl = new Hashtable(); hashtbl.Add("Number",1); hashtbl.Add("Car", "Ferrari"); hashtbl.Add(8, "eight"); } }
As you can see, we have added different datatypes as keys and values.
How To Access Elements Present In A HashTable?
One can retrieve the value of any key from the Hashtable using an indexer. But the indexer also requires a key to access and retrieve the value from the table.
Let’s add a small code snippet to the above program to fetch values:
class Program { static void Main(string[] args) { Hashtable hashtbl = new Hashtable(); hashtbl.Add("Number",1); hashtbl.Add("Car", "Ferrari"); hashtbl.Add(8, "eight"); int value1 = (int)hashtbl["Number"]; String value2 = (string)hashtbl["Car"]; String value3 = (string)hashtbl[8]; Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(value3); Console.ReadLine(); } }
Now if we execute this, the following output will be produced:
1
ferrari
eight
In the above program, we have cast the value of all the keys for a given data type, to remove any compilation error that may occur. This is because being a non-generic collection, Hashtable doesn’t contain information about the data type of any of its contents i.e. keys and values.
Hence, if we directly try to get the data compiler, we will get confused about the datatype and will throw an error.
How To Remove An Element From Hashtable?
Let’s say we want to remove a particular key-value pair from the Hashtable. To achieve this we have to use Remove() method offered by the collections. Remove method deletes a given key-value pair from the Hashtable permanently.
Remove(Key);
Let’s add the Remove method in the above program to get the idea:
class Program { static void Main(string[] args) { Hashtable hashtbl = new Hashtable(); hashtbl.Add("Number",1); hashtbl.Add("Car", "Ferrari"); hashtbl.Add(8, "eight"); int value1 = (int)hashtbl["Number"]; String value2 = (string)hashtbl["Car"]; String value3 = (string)hashtbl[8]; Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(value3); //now we remove a key hashtbl.Remove(8); //Lets try to find the remove key now String valueRemoved = (string)hashtbl[8]; Console.WriteLine("The value of the given key is :"+valueRemoved); Console.ReadLine(); } }
The output of the above program will be the following.
1
Ferrari
eight
The value of the given key is :
No, the value is printed to the console as we have removed the key from the Hashtable. Hence, the string value from valueRemoved is null.
If you want to remove everything from the hashtable, then C# provides us with another method called Clear(). Remove method deletes one key-value pair at a time whereas the Clear method deletes everything from the hashmap.
Let’s have a look at the below program to do this:
class Program { static void Main(string[] args) { Hashtable hashtbl = new Hashtable(); hashtbl.Add("Number",1); hashtbl.Add("Car", "Ferrari"); hashtbl.Add(8, "eight"); int value1 = (int)hashtbl["Number"]; String value2 = (string)hashtbl["Car"]; String value3 = (string)hashtbl[8]; Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(value3); //now we remove a key hashtbl.Remove(8); //Lets try to find the remove key now String valueRemoved = (string)hashtbl[8]; Console.WriteLine("The value of the given key is :"+valueRemoved); // clearing all data from the HashTable hashtbl.Clear(); Console.ReadLine(); } }
The above program will remove all the elements from the hashtable and will render it empty.
Other important methods offered by Hashtable is ContainsKey() and ContainsValue(). Both of these methods accept one argument which is a Key or a value and return a Boolean value. So, if the parameter passed with this method is present in the hashtable, then it will return a true value and if it’s not present then false will be returned.
C# SortedList
As the name suggests, SortedList contains sorted data in ascending order. It is similar to Hashtable as it contains similar key-value pair. All keys inserted or added to the SortedList are automatically arranged in ascending order.
How To Initialize A SortedList?
A SortedList can be initialized by using the keyword SortedList and creating an object instance for it.
SortedList sortedList = new SortedList();
The object can then be used for performing operations using the SortedList property and methods.
How To Add An Element To A SortedList?
You can add an element to a SortedList using the Add() method. A SortedList requires you to add a key and a value. You can add keys and values in any order you want and the sorted list will arrange all the added elements in ascending order.
class Program { static void Main(string[] args) { SortedList sortedList = new SortedList(); sortedList.Add(2, "Two Pineapples"); sortedList.Add(4, "Four Apples"); sortedList.Add(3, "Three Lemons"); sortedList.Add(5, "Five Mangoes"); sortedList.Add(1, "One Tree"); Console.ReadLine(); } }
In the above program, you can see that we have added integer as key and then string as the values. You can add any data type as you want and in any order you wish. The SortedList will arrange it in ascending order.
Similar to the HashTable, keys cannot be null and all the keys should have the same data type for comparison or else it will throw a compilation error.
The Sorted list sorts the element each time you add them. So, even if you add any element after the sorting has been done, it will again sort and add the element to its appropriate index.
How To Access The Elements From A SortedList?
A value in the Sorted List can be accessed by using the key.
Let’s add a simple code to fetch the value from the SortedList described in the previous example:
class Program { static void Main(string[] args) { SortedList sortedList = new SortedList(); sortedList.Add(2, "Two Pineapples"); sortedList.Add(4, "Four Apples"); sortedList.Add(3, "Three Lemons"); sortedList.Add(5, "Five Mangoes"); sortedList.Add(1, "One Tree"); string i = (string)sortedList[1]; string j = (string)sortedList[5]; string k = (string)sortedList[3]; Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); Console.ReadLine(); } }
The output of the above code snippet will be:
One Tree
Five Mangoes
Three Lemons
In the above code snippet, we have to cast the value of all the keys for a given data type to remove any compilation error that may occur with the data type of the value. This is done to ensure that a compilation error is not thrown, even if some of the keys contain different data types.
How To Validate If A Given Key Exists In A SortedList?
There are two inbuilt methods i.e. Contains() and ContainsKey() that help us in determining if a particular key exists inside a sortedList. ConstainsValue() is another method that is used to determine if a particular value is present inside the collection or not.
Let’s have a look at a simple program to learn more about these methods.
class Program { static void Main(string[] args) { SortedList sortedList = new SortedList(); sortedList.Add(2, "Two Pineapples"); sortedList.Add(4, "Four Apples"); sortedList.Add(3, "Three Lemons"); sortedList.Add(5, "Five Mangoes"); sortedList.Add(1, "One Tree"); //boolean value for key 5 bool key = sortedList.ContainsKey(5); //boolean value for vlaue "One Tree" bool val = sortedList.ContainsValue("One Tree"); //Boolean value for unavailable key bool unKey = sortedList.ContainsKey(25); //Boolean value for unavailable value bool unVal = sortedList.ContainsValue("some randome value"); Console.WriteLine("The sorted list contains 5 key :" + key); Console.WriteLine("The sorted list contains One Tree value :" + val); Console.WriteLine("The sorted list contains 25 key :" +unKey); Console.WriteLine("The sorted list contains some random value:" + unVal); Console.ReadLine(); } }
The output of the above program will be:
The sorted list contains 5 key : True
The sorted list contains One Tree value : True
The sorted list contains 25 key : False
The sorted list contains some random value: False
In the above program, you can clearly see that if the value or key is present inside the Sorted List, then a true value is returned and if it is absent then a false value is returned.
How To Remove An Element From The SortedList?
The sorted list offers Remove() and RemoveAt() methods to delete any element present inside a Sorted List. Remove accepts a single argument with the key name and RemoveAt also accepts a single argument but with index.
Both of these methods remove any element present inside the Sorted list based on the argument.
Let’s have a look at a simple code to understand it more clearly.
class Program { static void Main(string[] args) { SortedList sortedList = new SortedList(); sortedList.Add(2, "Two Pineapples"); sortedList.Add(4, "Four Apples"); sortedList.Add(3, "Three Lemons"); sortedList.Add(5, "Five Mangoes"); sortedList.Add(1, "One Tree"); //The Remove() method accepts key as argument and removes both the key and the value sortedList.Remove(1); //Now we will check if the key is present bool rmvKey = sortedList.ContainsKey(1); Console.WriteLine("The presence if the key is: " + rmvKey); //The RemoveAt() method acceots index as argument and remove any key and value present at that index sortedList.RemoveAt(3); Console.ReadLine(); } }
The output of the above program will be:
The presence if the key is: False
In the above program, we first used the Remove method to remove a key-value pair using the key. This will remove any key-value pair matching the key provided in the argument. Then we used the ContainsKey method to verify that the removed key no longer exists in the Sorted list.
In the next line, we used the RemoveAt method that removes elements using the index. Thus, as we discussed earlier once the particular element will be removed from the index, another element will move up to rearrange and maintain the sorted list structure.
Conclusion
Collections are dedicated classes present in the C# programming language to store and operate on data. These are used to perform specific actions i.e. to create dynamic lists, Reverse, Sort, etc. on a given data set.
In this tutorial, we learned about ArrayList which is similar to an array in some aspects but doesn’t have any predefined size. We also learned about HashTable that stores data in key-value pairs. Any value can be retrieved using the key.
We also learned about the sorted list which is similar to a HashTable but it automatically sorts all the data present inside it, in ascending order based on the keys.
The data inside the Sorted List is always in ascending order, i.e. even if you remove a particular element from the middle or add a new element to the Sorted List, it will automatically arrange all data in ascending order.
Sample Code
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SeleniumFrameWork.FrameworkEssentials; using SeleniumFrameWork.FrameWorkSupportModules; namespace ConsoleApp1 { class Program { static void Main(string[] args) { /* Array List Code */ ArrayList arrList = new ArrayList(); arrList.Add(7); arrList.Add(4); arrList.Add(5); arrList.Add(1); arrList.Add(3); Console.WriteLine("Original Array List"); foreach (var v in arrList) { Console.Write(v + " "); } //sorting an array list Console.WriteLine(); Console.WriteLine("Sorted Array List"); arrList.Sort(); foreach (var srt in arrList) { Console.Write(srt + " "); } //Reversing an array list Console.WriteLine(); Console.WriteLine("Reversed Array List"); arrList.Reverse(); foreach (var rvrs in arrList) { Console.Write(rvrs + " "); } /* HashTable Code */ Hashtable hashtbl = new Hashtable(); hashtbl.Add("Number", 1); hashtbl.Add("Car", "Ferrari"); hashtbl.Add(8, "eight"); int value1 = (int)hashtbl["Number"]; String value2 = (string)hashtbl["Car"]; String value3 = (string)hashtbl[8]; Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(value3); //now we remove a key hashtbl.Remove(8); //Lets try to find the remove key now String valueRemoved = (string)hashtbl[8]; Console.WriteLine("The value of the given key is :" + valueRemoved); // clearing all data from the HashTable hashtbl.Clear(); /* Sorted List Code */ SortedList sortedList = new SortedList(); sortedList.Add(2, "Two Pineapples"); sortedList.Add(4, "Four Apples"); sortedList.Add(3, "Three Lemons"); sortedList.Add(5, "Five Mangoes"); sortedList.Add(1, "One Tree"); string i = (string)sortedList[1]; string j = (string)sortedList[5]; string k = (string)sortedList[3]; Console.WriteLine(i); Console.WriteLine(j); Console.WriteLine(k); //boolean value for key 5 bool key = sortedList.ContainsKey(5); //boolean value for vlaue "One Tree" bool val = sortedList.ContainsValue("One Tree"); //Boolean value for unavailable key bool unKey = sortedList.ContainsKey(25); //Boolean value for unavailable value bool unVal = sortedList.ContainsValue("some randome value"); Console.WriteLine("The sorted list contains 5 key :" + key); Console.WriteLine("The sorted list contains One Tree value :" + val); Console.WriteLine("The sorted list contains 25 key :" +unKey); Console.WriteLine("The sorted list contains some randome value:" + unVal); //The Remove() method accepts key as argument and removes both the key and the value sortedList.Remove(1); //Now we will check if the key is present bool rmvKey = sortedList.ContainsKey(1); Console.WriteLine("The presence if the key is: " + rmvKey); //The RemoveAt() method acceots index as argument and remove any key and value present at that index sortedList.RemoveAt(3); Console.ReadLine(); } } }
=> Look For The Easy C# Training Guide Here