top

Search

C# Tutorial

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 CollectionThe different constructors and their description is given as follows:Table: Constructors in Dictionary Collection in C#Source: MSDNConstructorsDescriptionDictionary<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.Properties in Dictionary CollectionThe different properties and their description is given as follows:Table: Properties in Dictionary Collection in C#Source: MSDNPropertiesDescriptionComparerThis property gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.CountThis 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 keyItem[TKey]This property gets a collection containing the keys in the Dictionary<TKey,TValue>.ValuesThis property gets a collection containing the values in the Dictionary<TKey,TValue>.Methods in Dictionary CollectionThe different methods and their description is given as follows:Table: Methods in Dictionary Collection in C#Source: MSDNMethodsDescriptionAdd(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, TValueThis method gets the value associated with the specified key.Dictionary OperationsSome of the Dictionary operations are given as follows:Adding elements in DictionaryElements 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:Source Code: Program to add elements in Dictionary in C#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);        }      }   } }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: SusanDeleting elements from DictionaryAn 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:Source Code: Program to delete elements from Dictionary in C#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);        }      }   } }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: EmmaFinding an element in DictionaryThe 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:Source Code: Program to find an element in Dictionary in C#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"));      }   } }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: FalseInitialize a dictionary to an empty dictionaryUse the Clear() method to initialize a dictionary to an empty dictionary. Let us see an example:Source Code: Program to initialize a dictionary to an empty dictionary in C#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...");   }  } } }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:Source Code: Program to iterate over a C# Dictionary in C#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]);  } } }The above program gives the following output:1, 189 2, 145 3, 178 4, 199 5, 123 6, 156 7, 166 8, 185Get the List of keys from a Dictionary.Let us see the C# example to get the list of keys:Source Code: Program to get the list of keys from a Dictionary in C#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);        }    } }The above program gives the following output:1 2 3 4 5Convert a Collection into DictionaryTo convert a collection into Dictionary, use the ToDictionary() method as shown in the below example:Source Code: Program to convert a collection into Dictionary in C#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);        }    } }In the above example, the following is the output:Chair, True Table, TrueCombine Dictionary of two keysTo combine Dictionary, use another C# Collections i.e. HashSet. With that, implement the UnionsWith() method.Let us see an example:Source Code: Program to combine Dictionary of two keys in C#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);  } } }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);  } }
logo

C# Tutorial

Dictionary Collection in C#

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:

Table: Constructors in Dictionary Collection in C#

Source: MSDN

ConstructorsDescription
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.

Properties in Dictionary Collection

The different properties and their description is given as follows:

Table: Properties in Dictionary Collection in C#

Source: MSDN

PropertiesDescription
ComparerThis property gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.
CountThis 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>.
ValuesThis property gets a collection containing the values in the Dictionary<TKey,TValue>.

Methods in Dictionary Collection

The different methods and their description is given as follows:

Table: Methods in Dictionary Collection in C#

Source: MSDN

MethodsDescription
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, TValueThis method gets the value associated with the specified key.

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:

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

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);
       }
     }
  }
}

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:

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

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);
       }
     }
  }
}

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:

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

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"));
     }
  }
}

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:

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

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...");
  }
 }
}
}

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:

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

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]);
 }
}
}

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:

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

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);
       }
   }
}

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:

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

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);
       }
   }
}

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:

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

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);
 }
}
}

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);
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial