Open In App

C# | Dictionary Class

Last Updated : 01 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System.Collections.Generic namespace. The Dictionary <TKey, TValue> 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. Every key in a Dictionary <TKey, TValue> must be unique according to the dictionary’s equality comparer.

Note: A key cannot be null, but a value can be if the value type TValue is a reference type.

Parameters:  

  • TKey : Denotes the type of the keys in the dictionary.
  • TValue : Denotes the type of the values in the dictionary.

Since the Dictionary<TKey, TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair <TKey, TValue> of the key type and the value type.  

Constructors

Constructor Description
Dictionary<TKey, TValue>() Initializes a new 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. 
 
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Initializes a new instance of the Dictionary<TKey, TValue> class that contains elements copied from the specified IDictionary<TKey, TValue> and uses the default equality comparer for the key type.
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified IEqualityComparer<T>.
Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>.
Dictionary<TKey,TValue>(Int32) Initializes a new instance of the Dictionary class that is empty, has the specified initial capacity and uses the default equality comparer for the key type.
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>.
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

Example:

C#




// C# code to create a Dictionary
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict =
          new Dictionary<string, string>();
 
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
 
        // Displaying the key/value pairs in myDict
        Console.WriteLine("\nThe key/value pairs"+
                           " in myDict are : ");
 
        foreach(KeyValuePair<string, string> kvp in myDict)
        {
            Console.WriteLine("Key = {0}, Value = {1}",
                              kvp.Key, kvp.Value);
        }
    }
}


Output: 

Total key/value pairs in myDict are : 6

The key/value pairs in myDict are : 
Key = 1, Value = C
Key = 2, Value = C++
Key = 3, Value = Java
Key = 4, Value = Python
Key = 5, Value = C#
Key = 6, Value = HTML

 

Properties

Properties Description
Comparer Gets the IEqualityComparer<TKey, TValue> that is used to determine equality of keys for the dictionary.
Count Gets the number of key/value pairs contained in the Dictionary<TKey, TValue>.
Item[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>.

Example 1:

C#




// C# code to get the keys
// in the Dictionary
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict =
          new Dictionary<string, string>();
 
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
 
        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
                                              myDict.Keys;
 
        // The elements of the KeyCollection
        // are strongly typed with the type
        // that was specified for dictionary keys.
        foreach(string s in keyColl)
        {
            Console.WriteLine("Key = {0}", s);
        }
    }
}


Output: 

Total key/value pairs in myDict are : 6
Key = 1
Key = 2
Key = 3
Key = 4
Key = 5
Key = 6

 

Example 2:

C#




// C# code to get the values
// in the Dictionary
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict =
           new Dictionary<string, string>();
 
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
 
        // To get the values alone, use the Values property.
        Dictionary<string, string>.ValueCollection valueColl =
                                                myDict.Values;
 
        // The elements of the ValueCollection
        // are strongly typed with the type
        // that was specified for dictionary values.
        foreach(string s in valueColl)
        {
            Console.WriteLine("Value = {0}", s);
        }
    }
}


Output: 

Total key/value pairs in myDict are : 6
Value = C
Value = C++
Value = Java
Value = Python
Value = C#
Value = HTML

 

Methods

Method Description
Add(TKey, TValue) Adds the specified key and value to the dictionary. 
 
Clear() Removes all keys and values from the Dictionary<TKey, TValue>.
ContainsKey(TKey) Determines whether the Dictionary<TKey, TValue> contains the specified key.
ContainsValue(TValue) Determines whether the Dictionary<TKey, TValue> contains a specific value.
Equals(Object) Determines whether the specified object is equal to the current object. 
 
GetEnumerator() Returns an enumerator that iterates through the Dictionary<TKey, TValue> .
GetHashCode() Serves as the default hash function.
GetObjectData(SerializationInfo, StreamingContext) Implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.
GetType() Gets the Type of the current instance.
MemberwiseClone() Creates a shallow copy of the current Object.
OnDeserialization(Object) Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
Remove(TKey) Removes the value with the specified key from the Dictionary<TKey, TValue>.
ToString() Returns a string that represents the current object.
TryGetValue(TKey, TValue) Gets the value associated with the specified key.

Example 1:

C#




// C# code to remove all entries
//  from Dictionary
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict =
          new Dictionary<string, string>();
 
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs "+
                "in myDict are : " + myDict.Count);
 
        myDict.Clear();
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs in "+
             "myDict after Clear() operation are : " +
                                        myDict.Count);
    }
}


Output: 

Total key/value pairs in myDict are : 6
Total key/value pairs in myDict after Clear() operation are : 0

 

Example 2:

C#




// C# code to remove the entry with
// the specified key from the Dictionary
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict =
          new Dictionary<string, string>();
 
       // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs "+
                "in myDict are : " + myDict.Count);
 
        // Remove the entry with the
        // specified key from the Dictionary
        myDict.Remove("Russia");
 
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs in"+
          " myDict after Remove() operation are : " +
                                       myDict.Count);
    }
}


Output: 

Total key/value pairs in myDict are : 6
Total key/value pairs in myDict after Remove() operation are : 6

 

Reference: 

 



Similar Reads

C# Program to Check a Class is a Sub-Class of a Specified Class or Not
A class is a collection of methods, variables, and objects. A subclass is a class that is extended from the parent class. It should achieve all the properties from the parent class. Its syntax is similar to a class. Using: operator we can create the subclass. We can check the class is a subclass of the specific class or not by using the IsSubclassO
2 min read
C# | Dictionary.Add() Method
Dictionary&lt;TKey,TValue&gt;.Add() Method is used to add a specified key and value to the dictionary. Syntax: public void Add (TKey key, TValue value); Parameters: key: It is the key of the element to add. value: It is the value of the element to add. The value can be null for reference types. Exceptions: ArgumentNullException : If the key is null
3 min read
C# | Dictionary.ContainsValue() Method
This method is used to check whether the Dictionary&lt;TKey,TValue&gt; contains a specific value or not. Syntax: public bool ContainsValue (TValue value); Here, the value is the Value to locate in the Dictionary. The value can be null for reference types. Return Value: This method returns true if the Dictionary contains an element with the specifie
2 min read
C# | Dictionary.ContainsKey() Method
This method is used to check whether the Dictionary&lt;TKey,TValue&gt; contains the specified key or not. Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
2 min read
C# | Dictionary.Item[] Property
This property is used to get or set the value associated with the specified key in the Dictionary. Syntax: public TValue this[TKey key] { get; set; } Here, key is the Key of the value to get or set. Property Value: It is the value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, an
2 min read
C# | Dictionary.Values Property
This property is used to get a collection containing the values in the Dictionary&lt;TKey,TValue&gt;. Syntax: public System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;.KeyCollection Values{ get; } Return Value: This property returns a collection containing the Values in the Dictionary. Below are the programs to illustrate the use of Dictiona
2 min read
C# | Dictionary.Keys Property
This property is used to get a collection containing the keys in the Dictionary. Syntax: public System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;.KeyCollection Keys { get; } Return Value : It returns a collection containing the keys in the Dictionary. Below are the programs to illustrate the use of above-discussed property: Example 1: // C#
2 min read
C# | Dictionary.Remove Method
This method is used to remove the value with the specified key from the Dictionary&lt;TKey,TValue&gt;. Syntax: public bool Remove (TKey key); Return Value: This method returns true if the element is successfully found and removed; otherwise it returns false. This method returns false if key is not found in the Dictionary. Exception: This method wil
2 min read
C# | Dictionary.Clear Method
This method is used to remove all key/value pairs from the Dictionary&lt;TKey,TValue&gt;. Syntax: public void Clear (); Below are the programs to illustrate the use of above-discussed method: Example 1: // C# code to remove all pairs // from Dictionary using System; using System.Collections.Generic; class GFG { // Driver code public static void Mai
2 min read
C# | Dictionary.Count Property
This property is used to get the number of key/value pairs contained in the Dictionary. Syntax: public int Count { get; } Return Value : The number of key/value pairs contained in the Dictionary. Below are the programs to illustrate the use of above-discussed property: Example 1: // C# code to count the number of // key/value pairs in Dictionary us
2 min read