Table of contents
1.
C# Dictionary
2.
How to create the Dictionary?
2.1.
C#
3.
Methods of Dictionaries in C#
4.
Basic Operations of Dictionaries in C#
4.1.
1. Add or update elements
4.2.
C#
4.3.
2. Accessing key and values:
4.4.
C#
4.5.
3. Remove elements.
4.6.
C#
5.
Frequently Asked Questions
5.1.
What is dictionary of classes in C#?
5.2.
What is the difference between dictionary and Hashtable in C#?
5.3.
What is faster than dictionary in C#?
5.4.
What is the difference between array and dictionary in C#?
5.5.
When to use dictionary in C#?
6.
Conclusion
Last Updated: Jul 16, 2024
Easy

Dictionaries in C#

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

A key-value collection is a data storage structure that stores data as a set of unique identifiers, each mapped to a value. This is known as a “key-value pair”. They are typically much more flexible and offer very fast performance for reading and writing data. Dictionary as a data structure helps implement key-value pairings in C#. Let us learn more about this in detail.

Dictionaries in C#

C# Dictionary

The Dictionary class in C# is a generic collection of key-value pairs. It is defined in the System.Collections class. The Generic namespace can store any data type in the form of keys and values. Each key must be unique in the collection, using which a value can be accessed. Keys cannot be null, but values can be duplicated or null.

How to create the Dictionary?

The most common constructor used to create dictionaries is 

Dictionary<TKey, TValue>()

 

Where TKey is the data type of the key and TValue is the data type of the value.

Syntax:

//import statement
using System.Collection.Generics;
Dictionary<TKey, TValue>() = new Dictionary<TKey, TValue>();

 

Here is a simple example of creating dictionaries in C#.

  • C#

C#

using System;
using System.Collections.Generic;

class NewDictionary {

static public void Main ()
{
Dictionary<string, string> countries = new Dictionary<string, string>();
Console.WriteLine(countries);
}
}

Output:

System.Collections.Generic.Dictionary`2[System.String,System.String]

Methods of Dictionaries in C#

Method

Description

Add(key, value)Adds a key-value pair to the dictionary.
Clear()It clears all the key-value pairs in the dictionary.
Remove(key)It removes the specified key and its corresponding value from the dictionary.
ContainsKey(key)It checks if a given key exists in the dictionary.
ContainsValue(value)It checks if a given value exists in the dictionary.
CountIt returns the number of key-value pairs in the dictionary.

 

Basic Operations of Dictionaries in C#

1. Add or update elements

  • C#

C#

using System;
using System.Collections.Generic;

class NewDictionary{
static public void Main ()
{
Dictionary<string, string> countries = new Dictionary<string, string>(){
{"Australia","Canberra"},
{"Austria","Vienna"}
};

// Using Add() method
countries.Add("China","Hongkong");
countries.Add("Egypt","Giza");

// Printing key-value pairs
foreach(KeyValuePair<string, string> ele in countries)
{
Console.WriteLine("{0} and {1}",ele.Key, ele.Value);
}
Console.WriteLine();

    // Updating the values of selected keys
countries["Egypt"] = "Cairo";
    countries["China"] = "Beijing";

foreach(KeyValuePair<string, string> ele1 in countries)
{
Console.WriteLine("{0} and {1}", ele1.Key, ele1.Value);
}
}
}


Output:

Australia and Canberra
Austria and Vienna
China and Hongkong
Egypt and Giza

Australia and Canberra
Austria and Vienna
China and Beijing
Egypt and Cairo

 

2. Accessing key and values:

  • To get the value of a given key
dictionary_name[key]
  • To get the collection of keys in the dictionary
Dictionary<TKey, TValue>.KeyCollection keys = dictionary_name.Keys;
  • To get the collection of values in the dictionary.
Dictionary<TKey, TValue>.ValueCollection values = dictionary_name.Values;
  • To retrieve all key-value pairs as objects for traversal.
foreach (KeyValuePair<TKey, TValue> obj in dictionary_name)

Example

  • C#

C#

using System;
using System.Collections.Generic;

class NewDictionary{
static public void Main ()
{
Dictionary<string, string> countries = new Dictionary<string, string>(){
{"Australia","Canberra"},
{"Austria","Vienna"},
{"China","Beijing"}
};

// To display value of a key
Console.WriteLine("{0} is the capital of Austria\n", countries["Austria"]);

Dictionary<string,string>.KeyCollection keys = countries.Keys;

    // To display keys
foreach (string key in keys)
{
Console.WriteLine("key: {0}",key);
}
Console.WriteLine();

foreach(KeyValuePair<string, string> ele in countries)
{
Console.WriteLine("{0} and {1}", ele.Key, ele.Value);
}
}
}

Output:

Vienna is the capital of Austria

key: Australia
key: Austria
key: China

Australia and Canberra
Austria and Vienna
China and Beijing

3. Remove elements.

  • C#

C#

using System;
using System.Collections.Generic;

class NewDictionary{
static public void Main ()
{
Dictionary<string, string> countries = new Dictionary<string, string>(){
{"Australia","Canberra"},
{"Austria","Vienna"},
{"China","Beijing"}
};
 
  // To display number of key-value pairs
Console.WriteLine("Initial dictionary count: {0}", countries.Count);

foreach(KeyValuePair<string, string> ele in countries)
{
Console.WriteLine("{0} and {1}", ele.Key, ele.Value);
}

  // Removing elements
countries.Remove("Austria");
countries.Remove("Australia");

Console.WriteLine("\nAfter removing Austria and Australia: {0}", countries.Count);

foreach(KeyValuePair<string, string> ele in countries)
{
Console.WriteLine("{0} and {1}", ele.Key, ele.Value);
}
 
  //clears entire dictionary
  countries.Clear();
}
}


Output:

Initial dictionary count: 3
Australia and Canberra
Austria and Vienna
China and Beijing

After removing Austria and Australia: 1
China and Beijing

Frequently Asked Questions

What is dictionary of classes in C#?

A dictionary of classes in C# is a collection that associates unique keys with objects of a specific class type. It allows efficient retrieval and manipulation of objects based on their unique keys, providing a way to organize and access class instances in memory.

What is the difference between dictionary and Hashtable in C#?

The main difference lies in their implementation. While both store key-value pairs, a dictionary is a generic collection introduced in .NET Framework 2.0, offering type safety and better performance. Hashtable, on the other hand, is not type-safe and relies on boxing and unboxing, leading to potential performance overhead.

What is faster than dictionary in C#?

For scenarios requiring fast key-based lookups and memory efficiency, SortedDictionary or SortedList can be faster than Dictionary in C#. They maintain sorted order based on keys, offering efficient retrieval but may have slower insertion and deletion operations compared to Dictionary.

What is the difference between array and dictionary in C#?

An array in C# is a fixed-size collection of elements of the same data type, accessed using an index. In contrast, a dictionary is a dynamic collection that stores key-value pairs, allowing efficient retrieval of values based on unique keys. Arrays are indexed by integer values, while dictionaries are indexed by keys.

When to use dictionary in C#?

Use a dictionary in C# when you need to associate unique keys with values and require fast lookup operations based on those keys. It's particularly useful for scenarios involving data indexing, caching, or maintaining mappings between objects.

Conclusion

This article extensively discusses Dictionaries in C#. They play a crucial role in organizing and accessing data efficiently. They provide a powerful tool for associating unique keys with values, facilitating fast lookup operations and enabling various data manipulation tasks.

Also check out - Data Dictionary In Software Engineering

Recommended articles:

If you would like to learn more, check out our articles on the Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass