C# Dictionary – How to Use a Dictionary in C# [With Examples]

A Dictionary in C# is a collection that stores a set of keys and values, similar to a Hashtable. Dictionaries are useful for storing data that needs to be quickly retrieved using a key.

  • In C#, a Dictionary<TKey, TValue> is a generic collection that stores key/value pairs data organized by the unique key.
  • In C#, the Dictionary class is part of the System.Collections.Generic namespace. It is a dynamic collection that can be resized on-the-fly, allowing you to add or remove items as needed. It means that you don’t have to pre-define the size of the dictionary, and it can grow or shrink depending on the data being stored.
C# Dictionary
C# Dictionary

01. What Is a Dictionary in C#? 

A Dictionary<TKey, TValue> in C# is a generic collection of key-value pairs that are not sorted in an order. Each key in the dictionary is unique, and the value associated with that key can be accessed using the key. Dictionaries are a useful data structure when you need to quickly lookup a value based on its corresponding key.

Syntax

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

Here,

dictionary:Name of the Dictionary.
TKey:The type of key we pass in the dictionary.
TValue:The type of value we pass in the dictionary.

02. How to Create a Dictionary?

 Creating a dictionary in C# is easy. You can create an empty dictionary using the following code:

Dictionary<string, int> myDictionary = new Dictionary<string, int>();

In this example, we have created an empty dictionary that will store string keys and integer values.

03. How to Add Items to the Dictionary?

You can use the Add method to add an item to a dictionary. Here is an example:

myDictionary.Add("Jonny", 28);

In this example, we have added a key-value pair to the dictionary. The key is “Jonny”, and the value is 28.

04. How to Add Objects to the Dictionary?

Dictionaries can also store objects as values. Here is an example:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Dictionary<string, Person> people = new Dictionary<string, Person>();
people.Add("John", new Person { Name = "John", Age = 25 });

In the above example, we have created a dictionary that stores Person objects. We have added a Person object with a Name of “John” and an Age of 25.

05. How to Access an Item in the Dictionary?

You can use the square bracket notation to access an item in the dictionary.

Here is an example:

int jonnyAge = myDictionary["Jonny"];

In this example, we are retrieving the value associated with the key “Johnny” and storing it in a variable called jonnyAge.

06. How to Iterate Over the Dictionary?

You can iterate over a dictionary using a foreach loop. Here is an example:

foreach (KeyValuePair<string, int> item in myDictionary)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

Output:

Key: Jonny , Value: 28

In the above example, we are iterating over the key-value pairs in the dictionary using a foreach loop and writing them to the console.

07. How to Update an Item in a Dictionary?

To update an item in the dictionary, you can use the square bracket notation again. Here is an example:

myDictionary["Jonny"] = 29;

In the above example, we are updating the value associated with the key “Jonny” to 29.

08. How to Delete an Item in a Dictionary?

You can use the Remove method to delete an item in the dictionary. Here is an example:

myDictionary.Remove("Jonny");

In this example, we remove the key-value pair associated with the key “Jonny” from the dictionary.


Dictionary Characteristics

Here are some characteristics of Dictionary collections in C#:

  • Key-value pairs: The Dictionary<Tkey, TValue> is a generic collection that stores data in key-value pairs without any specific order.
  • No duplicate keys: A Dictionary does not allow duplicate keys. If you try to add a key-value pair with a key that already exists in the Dictionary, it will give you compile time error.
  • Empty values: A Dictionary can hold empty values, but the key cannot be empty.
  • Data types: The keys and values in a Dictionary must be of a designated data type. The data types for keys and values must be specified when creating the Dictionary.
  • Thread safety: By default, a Dictionary is not thread-safe. If you need a thread-safe collection, you can use a ConcurrentDictionary.
  • Namespace: You must import the System.Collections.Generic namespace before you can use the Dictionary class in your code.
  • Searching elements: we can easily search or remove elements from the Dictionary in C# using a key.

We can declare a generic dictionary using the following syntax:

C# Dictionary example 2

Here is an example of how to create and use a Dictionary in C#:

In the following code snippet, we will use the Add method to add key/value pair elements to a dictionary.

using System;
using System.Collections.Generic;

namespace DictionaryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new Dictionary with string keys and int values
            Dictionary<string, double> prices = new Dictionary<string, double>();

            // Add some key-value pairs to the dictionary
            prices.Add("Apple", 1.20);
            prices.Add("Banana", 0.80);
            prices.Add("Orange", 0.90);
            prices.Add("Papaya", 1.20);

            // Get the value associated with the key "Apple"
            double applePrice = prices["Apple"];
            Console.WriteLine($"The price of an apple is $ {applePrice}");

            // Change the value associated with the key "Banana"
            prices["Banana"] = 0.85;

            // Check if the dictionary contains a specific key
            if (prices.ContainsKey("Papaya"))
            {
                Console.WriteLine("The dictionary contains Papaya.");
            }

            // Iterate over the keys and values in the dictionary
            foreach (KeyValuePair<string, double> item in prices)
            {
                Console.WriteLine($"The price of {item.Key} is $ {item.Value}");
            }
            Console.ReadKey();
        }
    }
}

Output: This code will give you the following output:

The price of an apple is $ 1.2
The dictionary contains Papaya.
The price of Apple is $ 1.2
The price of Banana is $ 0.85
The price of Orange is $ 0.9
The price of Papaya is $ 1.2

Properties and methods of C# dictionary with examples

Here are some common properties and methods of Dictionary collections in C#, along with examples of how to use them:

C# Dictionary Properties

Count

Count: Gets the number of key-value pairs in the Dictionary.

            // Create a new Dictionary with string keys and int values
            Dictionary<string, double> prices = new Dictionary<string, double>();

            // Add some key-value pairs to the dictionary
            prices.Add("Apple", 1.20);
            prices.Add("Banana", 0.80);
            prices.Add("Orange", 0.90);
            prices.Add("Papaya", 1.20);

            // Count property
            int count = prices.Count; // count = 4

Keys

Keys: Gets a collection of all the keys in the Dictionary.

// Dictionary<string, double>.KeyCollection
var keys = prices.Keys; // keys = {"Apple", "Banana", "Orange","Papaya"}

Values

Values: Gets a collection of all the values in the Dictionary.

// Dictionary<string,double>.ValueCollection 
var values = prices.Values; // values = {1.20, 0.80, 0.90, 1.20}

C# Dictionary Methods

The following are the few methods of Dictionary collections in C# with examples.

Add()

Add(TKey key, TValue value): Adds a key-value pair to the Dictionary.

Dictionary<string, int> prices = new Dictionary<string, int>();
prices.Add("Apple", 1.20);
prices.Add("Banana", 0.80);

ContainsKey(TKey key)

ContainsKey(TKey key): Returns a boolean indicating whether the Dictionary contains the specified key.

bool containsApple = prices.ContainsKey("Apple"); // returns  true;
bool containsMango = prices.ContainsKey("Mango"); // returns false;

Note: If the key is null, an ArgumentNullException will be thrown, and if the requested key is not in the dictionary, a KeyNotFoundException will be thrown.

ContainsValue()

ContainsValue(TValue value): Returns a boolean indicating whether the Dictionary contains the specified value.

bool value = prices.ContainsValue(0.80); // returns true;

Remove()

Remove() method deletes the value with the specified key from the Dictionary.
If the key is found and the item is successfully removed, it returns true; otherwise false.

// Use the Remove method to remove a key / value pair.
Console.WriteLine("\nRemove(\"107\")\n");
prices.Remove("Apple");

// Check if item is removed from the dictionary object.
if (!prices.ContainsKey("Apple"))
{
  Console.WriteLine("Key \"107\" is not found.");
}

TryGetValue()

TryGetValue() : This method is used to get the value for a specific key, which allows you to handle the case where the key does not exist. It will not throw an error if the key doesn’t exist in the collection.

int mangoPrice;
if (prices.TryGetValue("Mango", out pearPrice))
{
    Console.WriteLine($"The price of a mango is {mangoPrice}.");
}
else
{
    Console.WriteLine("The price of a mango is not available.");
}

Clear()

Clear(): Removes all key-value pairs from the Dictionary.

prices.Clear(); // prices is now an empty dictionary

Summary:

The C# Dictionary class is a collection of key-value pairs that can store any data type. It belongs to the System.Collections.Generic namespace and requires that each key in the collection must be unique.


FAQ

Here are some frequently asked questions and answers about Dictionary collections in C#:

Q: When should you use a Dictionary in C#?

C# Dictionary is useful for storing data that needs to be quickly retrieved using a unique key.

Q: What is the difference between a Hashtable and a Dictionary in C#?

Hashtable is non-generic, so it can store key-value pairs of the same type or different data types, whereas Dictionary is a generic collection that can only store key-value pairs of the same type.

Q: What makes a dictionary faster than a hash table?

Retrieving data from a dictionary is much faster than with a hashtable because there is no boxing and unboxing.

Q: Can you store null values in a Dictionary?

Yes, you can store null values in a Dictionary. However, you cannot store a null key.

Q: Is a C# Dictionary thread-safe?

By default, a Dictionary is not thread-safe. If you need a thread-safe collection, you can use a ConcurrentDictionary.

Q: How can you iterate over the keys and values in a Dictionary?

You can use a foreach loop to iterate over the key-value pairs in a dictionary. You can access the key and value for each pair using the Key & Value properties of the KeyValuePair object.

foreach (KeyValuePair<string, int> item in prices) { Console.WriteLine($"The price of {item.Key} is {item.Value}."); }

Q: How can you check if a Dictionary contains a specific key or value?

You can use the ContainsKey method to check if a Dictionary contains a specific key, and the ContainsValue method to check if it contains a specific value.

Q: How can you get the value for a specific key in a C# Dictionary?

You can use the indexer (e.g. dict[key]) to get the value for a specific key in a Dictionary. If the key does not exist, a KeyNotFoundException will be thrown.

Conclusion:

In this article, we learned about the Dictionary in C# using multiple programming examples.

References: MSDN-Dictionary Class

Related Articles:

Shekh Ali
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments