This Tutorial Explains C# List And Dictionary with Examples. You will Learn How To Initialize, Populate And Access Elements in C# Dictionary and List:
In our earlier tutorial on C# Collections, we learned about types of collections present in the C# like ArrayList, Hashtable, Stack, SortedList, etc. The thing that is common among these collection types is that they can store any type of data item.
This seems quite useful for storing different data types inside a single collection entity but the downside is that while retrieving data from the collection, datacasting to an applicable data type is required. Without datacast, the program will throw a runtime exception and can hamper application.
=> FREE C# Training Tutorials For All
To resolve these issues, C# also offers generic collection classes. A generic collection offers better performance during storage and retrieval of the items.
Table of Contents:
C# List
We have already learned about the ArrayList in the previous articles. Basically, a List is similar to an ArrayList, the only difference being that the List is generic. The list has a unique property of extending its size as it grows, similar to the array list.
How To Initialize A List<>?
We can initialize a list in the following ways:
//using List type for initialization List<int> listInteger = new List<int>(); //using IList type for initialization IList<string> listString = new List<string>();
If you look at the above example you can see that in the first line we have used List<> to initialize an integer list. But in the second line, we have used IList<> for the initialization of the string list. You can use any of these for your program. The list is actually the implementation of the interface IList.
How To Add And Insert Element To The List<>?
Similar to the ArrayList we can add an element to the List by using the Add() method. The add method accepts data type value as an argument.
Syntax
ListName.Add(DataType value);
Let’s have a look at a simple program to add data to a list and IList.
Program:
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>;(); //Add elements to the list listInteger.Add(1); listInteger.Add(2); listInteger.Add(3); //using IList type for initialization IList<string> listString = new List<string>(); listString.Add("One"); listString.Add("Two"); listString.Add("Three"); Console.ReadLine(); } }
The element can also be added directly while initializing the List. We can directly add the value to the list at the time of initialization itself, in a similar way as we did it during our Arrays chapter.
This can be added by placing curly brackets after the List<> and then by writing the value inside it separated by commas. Let’s change the above program a little bit so that we can add the value directly during initialization.
So, our program will now look like:
class Program { static void Main(string[] args) { //using List type for initialization List<int>listInteger = new List<int>() {1,2,3}; //using IList type for initialization IList<string> listString = new List<string>(); listString.Add("One"); listString.Add("Two"); listString.Add("Three"); Console.ReadLine(); } }
In the above program, we initialized the integer list values at the start during initialization. It allowed us to pass the value directly without writing Add() method for each value. This is quite useful if we have a limited quantifiable amount of data that we need to put inside a list.
How To Access List<>?
We can access individual items from the list by using the index. The index can be passed in the square bracket after the name of the list.
Syntax
dataType Val = list_Name[index];
Now, let’s have a look at a simple program to get the data from the list that we created in our previous program.
Program
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; int val = listInteger[1]; Console.WriteLine(val); } }
The output of the following program will be the value at index 1. The index starts from 0, the output will be:
2
Now, let’s say we want to get all the data from the List, we can do this by using the for-each loop or for a loop.
For Each Loop
We can use for each loop to get all the data from the list.
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; foreach (var val in listInteger) { Console.WriteLine(val); } } }
Here we have looped through the list using for each loop by declaring a variable value. This will allow for each loop through the list until there is some data inside it.
For Loop
For using for loop we need to know the number of elements present inside the list. Count() method can be used to get the count of the element.
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; //finding the size of the list using count int size = listInteger.Count; for (int i =0; i< size; i++) { int val = listInteger[i]; Console.WriteLine(val); } } }
Sometime we may also need to insert a new element inside the list. To do that we need to use Insert() method to add new method anywhere inside the list. The insert method accepts two arguments, the first one is the index at which you want to insert the data and the second one being the data that you want to insert.
The syntax for the insert is:
List_Name.Insert(index, element_to_be_inserted);
Now, let’s insert an element inside the list we created earlier. We will add an insert statement to the above program and will try to see how it works:
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; //finding the size of the list using count int size = listInteger.Count; for (int i =0; i< size; i++) { int val = listInteger[i]; Console.WriteLine(val); } //Inserting the new value at index 1 listInteger.Insert(1, 22); //using foreach loop to print all values from list Console.WriteLine("List value after inserting new val"); foreach (var val in listInteger) { Console.WriteLine(val); } Console.ReadLine(); } }
If we execute the above program the output will be:
1
2
3
List value after inserting new val
1
22
2
3
After the for loop, we added the insert statement to insert integer 22 at index 1 in the previously defined list. Then we wrote a for each loop to print all the elements now present inside the list (After inserting the first data).
We can clearly see from the output that all the elements of the list have been shifted forward to make way for the new element at index 1. The index 1 now has 22 as an element and the previous element at index 1 i.e. 2 has shifted to the next index and so on.
How To Remove An Element From List<>?
Sometime, we may also require to remove items from the list. To do that C# offers two different methods. These two methods are Remove() and RemoveAt(). Remove is used to remove a certain element from the list and RemoveAt is used to remove any element present at the given index.
Let’s have look at the syntax.
Syntax
Remove(Element name); RemoveAt(index);
Now, let’s add Remove statement to the previous code and see what happens.
class Program { static void Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; //finding the size of the list using count int size = listInteger.Count; for (int i =0; i< size; i++) { int val = listInteger[i]; Console.WriteLine(val); } Console.WriteLine("Removing value from the list"); listInteger.Remove(2); foreach (var val in listInteger) { Console.WriteLine(val); } Console.ReadLine(); } }
The output of the above program will be:
1
2
3
Removing value from the list
1
3
In the above program, we have used the remove method to remove element 2 from the list. As you can see in the output once the Remove method has been executed, the list no longer contains the element that we removed.
Similarly, we can also use, RemoveAt method. Let’s replace the Remove method in the above program with RemoveAt() method and pass index number as the parameter.
class Program { staticvoid Main(string[] args) { //using List type for initialization List<int> listInteger = new List<int>() {1,2,3}; //finding the size of the list using count int size = listInteger.Count; for (int i =0; i< size; i++) { int val = listInteger[i]; Console.WriteLine(val); } Console.WriteLine("Removing value from the list"); //Removing the element present at index 2 listInteger.RemoveAt(2); foreach (var val in listInteger) { Console.WriteLine(val); } Console.ReadLine(); } }
The output of the above program will be:
1
2
3
Removing value from the list
1
2
In the above program, you can clearly see that we have removed the element present at index 2 rather than removing the integer 2. Hence, depending upon the requirement one can use either Remove() or RemoveAt() to remove a certain element from a list.
C# Dictionary
Dictionary in C# is similar to the Dictionary we have in any language. Here also we have a collection of words and their meanings. The words are known as key and their meanings or definition can be defined as values.
Dictionary accepts two arguments, the first one is key and the second one is value. It can be initialized by using a variable of either Dictionary class or IDictionary interface.
The syntax for Dictionary is:
Dictionary<Key, Value>
Let’s have a look at a simple program to initialize Dictionary:
Dictionary<string, string> data = new Dictionary<string, string>();
In the above program, you can clearly see that we have initialized the dictionary data with both key and value as a string. But you can use any data type pair for keys and values. For Example, if we change the above statement to contain a different data type then also it will be correct.
Dictionary<string, int> data = new Dictionary<string, int>();
The data type inside the angular bracket is for keys and values. You can keep any data type as key and value.
How To Add Keys And Values To A Dictionary?
We saw how we can initialize a dictionary. Now we will add keys and their values to the dictionary. The dictionary is quite useful when you want to add different data and their values in a list. The Add() method can be used to add data to the dictionary.
Syntax
DictionaryVariableName.Add(Key, Value);
Now, let us include the Add statement in the above program to add keys and values to the dictionary.
Program
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); } }
In the above program, we have used the Add() method to add the key and values to the dictionary. The first parameter passed to the Add() method is the key and the second parameter is the value of the key.
How To Access Keys And Values From A Dictionary?
As discussed in our tutorial on the list, we can also access elements from the dictionary in several different ways. We will discuss a few of the important ways in which we can access it here. We will discuss for loop, for each loop and index for accessing data items.
The index can be used to access specific values from the list.
For loop can be used to access or retrieve all the elements from the dictionary but requires the size of the dictionary to stop the loop. For each loop is more flexible, it can retrieve all the data present from the dictionary without requiring the size of the dictionary.
Using Indexing
An element from the index can be used similar to an array to access the element, the basic difference being that instead of index we need keys to access the values.
Syntax
Dictionary_Name[key];
Program
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); string value = dctn["two"]; Console.WriteLine(value); Console.ReadLine(); } }
The output of the above program will be:
second
Using For Loop For Accessing Element
The for loop can be used to access all the elements of the dictionary. But it also needs to get the count of the element inside the dictionary for a number of iteration required.
Let’s add for loop to the above program to retrieve all the values from the dictionary.
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); for(int i =0; i< dctn.Count; i++) { string key = dctn.Keys.ElementAt(i); string value = dctn[key]; Console.WriteLine("The element at key : " + key + " and its value is: " + value); } Console.ReadLine(); } }
The output of the above program will be:
The element at key: one and its value is: first
The element at key: two and its value is: second
The element at key: three and its value is: Third
In the above program, we have used the ElementAt() method to get the key at a given index, then we used the same key to retrieve the data of the key value. The for loop iterates through all the data inside the dictionary. Count property has been used to get the size of the dictionary for iteration.
Using For-Each Loop
Similar to for loop, we can also use the for each loop.
Let’s have a look at the above program with the for-each loop.
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); foreach (KeyValuePair<string, string> item in dctn) { Console.WriteLine("The Key is :"+ item.Key+" - The value is: "+ item.Value); } Console.ReadLine(); } }
The output of the above program will be:
The Key is : one – The value is: first
The Key is : two – The value is: second
The Key is : three – The value is: Third
The above program uses KeyValuePair to declare the variable, then we iterate through each of the key-value pairs in the dictionary and print that to the console.
How To Validate The Presence Of Data In A Dictionary?
Sometimes we need to verify if a certain key or value exists in the dictionary or not. We can validate this by using two methods i.e. ContainsValue() and ContainsKey() to check for the existing key or value inside the dictionary.
Contains method is used to validate if the given value is present in the dictionary or not. ContainsKey method is used to check if a given key exists in the dictionary or not.
Syntax
Dictionary_Name.ContainsValue(Value); Dictionary_Name.ContainsKey(Key);
Let us write a simple program to validate using the Contains and ContainsKey method.
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); bool key = dctn.ContainsKey("one"); bool val = dctn.ContainsValue("four"); Console.WriteLine("The key one is available : " + key); Console.WriteLine("The value four is available : " + val); Console.ReadLine(); } }
The output of the above program will be:
The key one is available: True
The value four is available: False
In the above program, we first used the ContainsKey method to validate if the given key is present inside the dictionary. As the key is present in the dictionary, the method returns true. Then we use ContainsValue to determine if the given value is present or not. As the value “four” is not present inside the dictionary, it will return false.
How To Remove An Element From A Dictionary?
There may be a time when we will require to remove a certain key-value pair from the dictionary to fulfill certain programming logic. Remove method can be used to remove any pair from the dictionary based on the key.
Syntax
Remove(key);
Program
class Program { static void Main(string[] args) { Dictionary<string, string> dctn = new Dictionary<string, string>(); dctn.Add("one", "first"); dctn.Add("two", "second"); dctn.Add("three", "Third"); //removing key two dctn.Remove("two"); //validating if the key is present or not bool key = dctn.ContainsKey("two"); Console.WriteLine("The key two is available : " + key); Console.ReadLine(); } }
The output of the above program will be:
The key two is available: False
In the above program first, we have added a key-value pair to the dictionary. Then we removed a key from the dictionary, and we used the ContainsKey() method to validate if the key-value pair is no longer present in the dictionary.
Conclusion
The List stores elements of the specific data type and grow as items are added. It can also store multiple duplicate elements. We can easily access items inside the List by using index, or loops. The list is very helpful in storing a large amount of data.
A Dictionary is used to store key-value pairs. Here the keys must be unique. Values from the dictionary can be retrieved using a loop or index. We can also validate keys or values using the Contains method.
=> Watch The Full C# Training Series Here