In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need. Important Points:
- The Dictionary class implements the
- IDictionary<TKey,TValue> Interface
- IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface
- IReadOnlyDictionary<TKey,TValue> Interface
- IDictionary Interface
- In Dictionary, the key cannot be null, but value can be.
- In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception.
- In Dictionary, you can only store same types of elements.
- The capacity of a Dictionary is the number of elements that Dictionary can hold.
How to create the Dictionary?
Dictionary class has 7 constructors which are used to create the Dictionary, here we only use Dictionary<TKey, TValue>() constructor and if you want to learn more about constructors then refer C# | Dictionary Class. Dictionary<TKey, TValue>(): This constructor is used to create an instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type as follows: Step 1: IncludeSystem.Collections.Generic namespace in your program with the help of using keyword. Syntax:
using System.Collections.Generic;
Step 2: Create a Dictionary using Dictionary<TKey, TValue> class as shown below:
Dictionary dictionary_name = new Dictionary();
Step 3: If you want to add elements in your Dictionary then use Add() method to add key/value pairs in your Dictionary. And you can also add key/value pair in the dictionary without using Add method. As shown in the below example. Step 4: The key/value pair of the Dictionary is accessed using three different ways:
- for loop: You can use for loop to access the key/value pairs of the Dictionary. Example:
CSharp
for ( int x=0; x< My_dict1.Count; x++)
{
Console.WriteLine("{0} and {1}", My_dict1.Keys.ElementAt(x),
My_dict1[ My_dict1.Keys.ElementAt(x)]);
}
|
- Using Index: You can access individual key/value pair of the Dictionary by using its index value. Here, you just specify the key in the index to get the value from the given dictionary, no need to specify the index. Indexer always takes the key as a parameter, if the given key is not available in the dictionary, then it gives KeyNotFoundException. Example:
CSharp
Console.WriteLine("Value is :{0}", My_dicti[1123]);
Console.WriteLine("Value is :{0}", My_dicti[1125]);
|
- foreach loop: You can use foreach loop to access the key/value pairs of the dictionary.As shown in the below example we access the Dictionary using a foreach loop.
Example:
CSharp
using System;
using System.Collections.Generic;
class GFG {
static public void Main () {
Dictionary< int , string > My_dict1 =
new Dictionary< int , string >();
My_dict1.Add(1123, "Welcome");
My_dict1.Add(1124, "to");
My_dict1.Add(1125, "GeeksforGeeks");
foreach (KeyValuePair< int , string > ele1 in My_dict1)
{
Console.WriteLine("{0} and {1}",
ele1.Key, ele1.Value);
}
Console.WriteLine();
Dictionary< string , string > My_dict2 =
new Dictionary< string , string >(){
{"a.1", "Dog"},
{"a.2", "Cat"},
{"a.3", "Pig"} };
foreach (KeyValuePair< string , string > ele2 in My_dict2)
{
Console.WriteLine("{0} and {1}", ele2.Key, ele2.Value);
}
}
}
|
Output:
1123 and Welcome
1124 and to
1125 and GeeksforGeeks
a.1 and Dog
a.2 and Cat
a.3 and Pig
How to remove elements from the Dictionary?
In Dictionary, you are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:
- Clear: This method removes all keys and values from the Dictionary<TKey,TValue>.
- Remove: This method removes the value with the specified key from the Dictionary<TKey,TValue>.
Example:
CSharp
using System;
using System.Collections.Generic;
class GFG {
static public void Main() {
Dictionary< int , string > My_dict =
new Dictionary< int , string >();
My_dict.Add(1123, "Welcome");
My_dict.Add(1124, "to");
My_dict.Add(1125, "GeeksforGeeks");
foreach (KeyValuePair< int , string > ele in My_dict)
{
Console.WriteLine("{0} and {1}",
ele.Key, ele.Value);
}
Console.WriteLine();
My_dict.Remove(1123);
foreach (KeyValuePair< int , string > ele in My_dict)
{
Console.WriteLine("{0} and {1}",
ele.Key, ele.Value);
}
Console.WriteLine();
My_dict.Clear();
Console.WriteLine("Total number of key/value "+
"pairs present in My_dict:{0}", My_dict.Count);
}
}
|
Output:
1123 and Welcome
1124 and to
1125 and GeeksforGeeks
1124 and to
1125 and GeeksforGeeks
Total number of key/value pairs present in My_dict:0
How to check the availability of elements in the Dictionary?
In Dictionary, you can check whether the given key or value present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods for checking and the methods are:
- ContainsKey: This method is used to check whether the Dictionary<TKey,TValue> contains the specified key.
- ContainsValue: This method is used to check whether the Dictionary<TKey,TValue> contains a specific value.
Example:
CSharp
using System;
using System.Collections.Generic;
class GFG {
static public void Main () {
Dictionary< int , string > My_dict =
new Dictionary< int , string >();
My_dict.Add(1123, "Welcome");
My_dict.Add(1124, "to");
My_dict.Add(1125, "GeeksforGeeks");
if (My_dict.ContainsKey(1122)== true )
{
Console.WriteLine("Key is found...!!");
}
else
{
Console.WriteLine("Key is not found...!!");
}
if (My_dict.ContainsValue("GeeksforGeeks")== true )
{
Console.WriteLine("Value is found...!!");
}
else
{
Console.WriteLine("Value is not found...!!");
}
}
}
|
Output:
Key is not found...!!
Value is found...!!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!