10X Sale
kh logo
All Courses
  1. Tutorials
  2. Programming Tutorials

Dictionary Collection in C#

Updated on Sep 3, 2025
 
46,000 Views

The dictionary collection represents Key-Value pairs. It is similar to an English dictionary with different words and their meanings. The dictionary collection is included in the System.Collections.Generic namespace.

Constructors in Dictionary Collection

The different constructors and their description is given as follows:

Constructors

Description

Dictionary<TKey,TValue>()

This constructor 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>)

This constructor 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>)

This constructor 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>)

This constructor 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)

This constructor initializes a new instance of the Dictionary<TKey,TValue> 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>)

This constructor 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)

This constructor initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

Table: Constructors in Dictionary Collection in C#
Source: MSDN

Properties in Dictionary Collection

The different properties and their description is given as follows:

Properties

Description

Comparer

This property gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.

Count

This property gets the number of key/value pairs contained in the Dictionary<TKey,TValue>.

Item[TKey]

This property gets or sets the value associated with the specified key

Item[TKey]

This property gets a collection containing the keys in the Dictionary<TKey,TValue>.

Values

This property gets a collection containing the values in the Dictionary<TKey,TValue>.

Table: Properties in Dictionary Collection in C#
Source: MSDN

Methods in Dictionary Collection

The different methods and their description is given as follows:

Methods

Description

Add(TKey, TValue)

This method adds the specified key and value to the dictionary.

Clear()

This method removes all keys and values from the Dictionary<TKey,TValue>.

ContainsKey(TKey)

This method determines whether the Dictionary<TKey,TValue> contains the specified key.

ContainsValue(TValue)

This method determines whether the Dictionary<TKey,TValue> contains a specific value.

Equals(Object)

This method determines whether the specified object is equal to the current object.

GetEnumerator()

This method returns an enumerator that iterates through the Dictionary<TKey,TValue>

GetHashCode()

This method serves as the default hash function.

GetObjectData(SerializationInfo, StreamingContext)

This method implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.

GetType()

This method gets the Type of the current instance.

MemberwiseClone()

This method creates a shallow copy of the current Object.

OnDeserialization(Object)

This method implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(TKey)

This method removes the value with the specified key from the Dictionary<TKey,TValue>.

ToString()

This method returns a string that represents the current object.

TryGetValue(TKey, TValue

This method gets the value associated with the specified key.

Table: Methods in Dictionary Collection in C#
Source: MSDN

Dictionary Operations

Some of the Dictionary operations are given as follows:

Adding elements in Dictionary

Elements can be added to the dictionary using the Add() method. It adds the specified key and value pairs to the dictionary. The program that demonstrates this is given as follows:

using System;
using System.Collections.Generic;
namespace DictionaryDemo
{
  class Example
  {
     static void Main(string[] args)
     {
       Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1,"Harry");
d.Add(2,"Sally");
d.Add(3,"Clarke");
d.Add(4,"James");
d.Add(5,"Emma");
d.Add(6,"Susan");
       Console.WriteLine("Dictionary elements are as follows:");
       foreach (KeyValuePair<int, string> i in d)
       {
           Console.WriteLine("Key: {0}     Value: {1}", i.Key, i.Value);
       }
     }
  }
}

Source Code: Program to add elements in Dictionary in C#

The output of the above program is given below:

Dictionary elements are as follows:
Key: 1     Value: Harry
Key: 2     Value: Sally
Key: 3     Value: Clarke
Key: 4     Value: James
Key: 5     Value: Emma
Key: 6     Value: Susan

Deleting elements from Dictionary

An element can be deleted from the Dictionary using the Remove() method. This method deletes the key, value pair with the specific key that is provided. The program that demonstrates this is given as follows:

using System;
using System.Collections.Generic;
namespace DictionaryDemo
{
  class Example
  {
     static void Main(string[] args)
     {
       Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1,"Harry");
d.Add(2,"Sally");
d.Add(3,"Clarke");
d.Add(4,"James");
d.Add(5,"Emma");
d.Add(6,"Susan");
       Console.WriteLine("Original dictionary elements:");
       foreach (KeyValuePair<int, string> i in d)
       {
           Console.WriteLine("Key: {0}     Value: {1}", i.Key, i.Value);
       }
       d.Remove(3);
       d.Remove(6);
       Console.WriteLine("Dictionary elements after deletion:");
       foreach (KeyValuePair<int, string> i in d)
       {
           Console.WriteLine("Key: {0}     Value: {1}", i.Key, i.Value);
       }
     }
  }
}

Source Code: Program to delete elements from Dictionary in C#

The output of the above program is given below:

Original dictionary elements:
Key: 1     Value: Harry
Key: 2     Value: Sally
Key: 3     Value: Clarke
Key: 4     Value: James
Key: 5     Value: Emma
Key: 6     Value: Susan
Dictionary elements after deletion:
Key: 1     Value: Harry
Key: 2     Value: Sally
Key: 4     Value: James
Key: 5     Value: Emma

Finding an element in Dictionary

The ContainsKey() method finds if a key is present in the Dictionary or not. If it is present, ContainsKey() returns TRUE and otherwise it returns FALSE. Similarly, ContainsValue() finds if a value is present in the Dictionary or not. If it is present, ContainsValue() returns TRUE and otherwise it returns FALSE.

The program that demonstrates this is given as follows:

using System;
using System.Collections.Generic;
namespace DictionaryDemo
{
  class Example
  {
     static void Main(string[] args)
     {
       Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1,"Harry");
d.Add(2,"Sally");
d.Add(3,"Clarke");
d.Add(4,"James");
d.Add(5,"Emma");
d.Add(6,"Susan");
       Console.WriteLine("Dictionary elements:");
       foreach (KeyValuePair<int, string> i in d)
       {
           Console.WriteLine("Key: {0}     Value: {1}", i.Key, i.Value);
       }
       Console.WriteLine();
       Console.WriteLine("The key 3 is present in Dictionary: " + d.ContainsKey(3));
       Console.WriteLine("The value Lucy is present in Dictionary: " + d.ContainsValue("Lucy"));
     }
  }
}

Source Code: Program to find an element in Dictionary in C#

The output of the above program is given below:

Dictionary elements:
Key: 1     Value: Harry
Key: 2     Value: Sally
Key: 3     Value: Clarke
Key: 4     Value: James
Key: 5     Value: Emma
Key: 6     Value: Susan

The key 3 is present in Dictionary: True
The value Lucy is present in Linked List: False

Initialize a dictionary to an empty dictionary

Use the Clear() method to initialize a dictionary to an empty dictionary. Let us see an example:

using System;
using System.Collections.Generic;
using System.Linq;
namespace Example {
public class Demo {
 public static void Main(string[] args) {
  var d = new Dictionary < string,string > ();
  d.Clear();
  if (d.Count == 0) {
   Console.WriteLine("Empty...");
  }
 }
}
}

Source Code: Program to initialize a dictionary to an empty dictionary in C#

The above example gives the following output:

Empty...

Iterate over a Dictionary in C#

To iterate over a C# Dictionary, you can consider using another collection i.e. List. Let us see how to implement it:

using System;
using System.Collections.Generic;
public class Example {
public static void Main() {
 IDictionary < int, int > dict = new Dictionary < int, int > ();
 dict.Add(1, 189);
 dict.Add(2, 145);
 dict.Add(3, 178);
 dict.Add(4, 199);
 dict.Add(5, 123);
 dict.Add(6, 156);
 dict.Add(7, 166);
 dict.Add(8, 185);
 List < int > l = new List < int > (dict.Keys);
 foreach(int res in l) {
  Console.WriteLine("{0}, {1}", res, dict[res]);
 }
}
}

Source Code: Program to iterate over a C# Dictionary in C#

The above program gives the following output:

1, 189
2, 145
3, 178
4, 199
5, 123
6, 156
7, 166
8, 185

Get the List of keys from a Dictionary.

Let us see the C# example to get the list of keys:

using System;
using System.Collections.Generic;
public class Demo
{
   public static void Main()
   {
       Dictionary<int, string> dict = new Dictionary<int, string>();
       dict.Add(1, "One");
       dict.Add(2, "Two");
       dict.Add(3, "Three");
       dict.Add(4, "Four");
       dict.Add(5, "Five");
       List<int> k = new List<int>(dict.Keys);
       foreach (int keys in k)
       {
          Console.WriteLine(keys);
       }
   }
}

Source Code: Program to get the list of keys from a Dictionary in C#

The above program gives the following output:

1
2
3
4
5

Convert a Collection into Dictionary

To convert a collection into Dictionary, use the ToDictionary() method as shown in the below example:

using System;
using System.Linq;
using System.Collections.Generic;
class Example
{
   static void Main()
   {
      string[] s = new string[] {"Chair", "Table"};
       var dict = s.ToDictionary(i => i, i => true);
       foreach (var res in dict)
       {
           Console.WriteLine("{0}, {1}",  res.Key, res.Value);
       }
   }
}

Source Code: Program to convert a collection into Dictionary in C#

In the above example, the following is the output:

Chair, True
Table, True

Combine Dictionary of two keys

To combine Dictionary, use another C# Collections i.e. HashSet. With that, implement the UnionsWith() method.

Let us see an example:

using System;
using System.Collections.Generic;
public class Example {
public static void Main() {
 Dictionary < string, int > d1 = new Dictionary < string, int > ();
 d1.Add("AB", 1);
 d1.Add("BC", 2);
 d1.Add("CD", 3);
 d1.Add("EF", 4);
 d1.Add("GH", 5);
 d1.Add("IJ", 6);
 Dictionary < string, int > d2 = new Dictionary < string, int > ();
 d2.Add("KL", 7);
 d2.Add("MN", 8);
 d2.Add("OP", 9);
 d2.Add("QR", 10);
 HashSet < string > h = new HashSet < string > (d1.Keys);
 h.UnionWith(d2.Keys);
 foreach(string res in h) {
  Console.WriteLine(res);
 }
}
}

Source Code: Program to combine Dictionary of two keys in C#

The above program gives the following output:

using System;
using System.Collections.Generic;
public class Example {
public static void Main() {
 Dictionary < string, int > d1 = new Dictionary < string, int > ();
 d1.Add("AB", 1);
 d1.Add("BC", 2);
 d1.Add("CD", 3);
 d1.Add("EF", 4);
 d1.Add("GH", 5);
 d1.Add("IJ", 6);
 Dictionary < string, int > d2 = new Dictionary < string, int > ();
 d2.Add("KL", 7);
 d2.Add("MN", 8);
 d2.Add("OP", 9);
 d2.Add("QR", 10);
 HashSet < string > h = new HashSet < string > (d1.Keys);
 h.UnionWith(d2.Keys);
 foreach(string res in h) {
  Console.WriteLine(res);
 }
}
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses