In this article, we will learn about the dictionaries in C#.
A dictionary is a collection of keys and values.
The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.
We create a Dictionary C# using the following syntax:
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
<TKey>
here denotes any datatype of the Key which we want to create a dictionary of.
Similiarly, <TValue>
denotes any datatype of the Value
Count
: This property gets the number of keys actually contained in the dictionary.Comparer
: Determines equality for the keys in the dictionary.Dict[TKey]
: Gets or sets the value associated with the specified key.Keys
: Gets a collection containing the keys in the Dictionary<TKey,TValue>.Values
: Gets a collection containing the values in the Dictionary<TKey,TValue>.Add(TKey, TValue)
: Adds the specified key and value to the dictionary.ContainsKey(TKey)
: Determines whether the Dictionary<TKey,TValue> contains the specified key.ContainsValue(TValue)
: Determines whether the Dictionary<TKey,TValue> contains a specific value.Remove(TKey)
: Removes the value with the specified key from the Dictionary<TKey,TValue>.Clear()
: Removes all keys and values from the Dictionary<TKey,TValue>.Different Dictionary operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace DictionaryDemo {
class Example {
static void Main(string[] args) {
Dictionary < int, int > D = new Dictionary < int, int > ();
D.Add(5, 1);
// D.Add(5, 2); will throw an error
// because 5 has already been added
D[5] = 2;
D[2] = 10; // We can use indexing property to add elements
D[10] = 3;
Console.WriteLine(D.Count); // Prints 3 because 5 is only added once in the dictionary
Console.WriteLine(D[5]); // Prints 2, the last entered value for 5.
Console.WriteLine(D.ContainKey(5)); // Checks if 5 is present
D.Remove(5); // Removes 5
Console.WriteLine(D.ContainsKey(5)); // Prints False this time
D[2]++;
Console.WriteLine(D[2]); // Prints 11 as we performed an arithmetic operation
// on a value present in a dictionary
foreach(int i in D.Keys) { // Prints all the Keys
Console.Write(i + " ");
}
Console.WriteLine();
}
}
}
Output:
3
2
True
False
11
2 10
2 5 9
In the editor below, perform the different tasks as directed.