• PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# Dictionary

last modified July 5, 2023

C# Dictionary tutorial shows how to work with a Dictionary collection in C#.

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

C# Dictionary initializers

C# dictionaries can be initialized with literal notation. The elements are added on the right side of the assignment inside {} brackets.

In the example, we create two dictionaries using literal notation.

A new dictionary is created. Between the angle brackets <> , we specify the data type of the keys and values. New pairs of key/value elements are written inside nested {} brackets; each pair is separated by a comma character. For instance, the "sk" key refers to the "Slovakia" value.

To get a value, we specify the dictionary name followed by square [] brackets. Between the brackets, we specify the key name.

This is an alternative C# dictionary initializer. The values are assigned to keys using dictionary access notation.

C# Dictionary count elements

With the Count property, we get the number of keys in the dictionary.

The example counts the number of items in the dictionary.

Here we print the number of items in the dictionary.

C# Dictionary add, remove elements

After the dictionary has been created, new elements can be added or removed from the dictionary.

The example creates a new dictionary and modifies it using several built-in methods.

A new dictionary is created. The user names are the keys and the user ages are the values.

We add two new pairs to the dictionary using dictionary access notation and the Add method.

We use the string Join method to display all elements in one shot.

A pair is removed with the Remove method. The parameter is the dictionary key.

The dictionary is cleared with the Clear method.

C# Dictionary ContainsKey and ContainsValue methods

The ContainsKey method determines whether the dictionary contains the specified key and the ContainsValue method determines whether the dictionary contains the specified value.

In the example, we check if the "sk" key and "Slovakia" value are present in the dictionary.

C# traverse dictionary

There are several ways to travers a C# dictionary.

The example loops over a dictionary using foreach .

In this foreach loop, we go through the dictionary by pairs. Each pair is decomposed into its key and value.

In this case, we access the keys and values by their Key and Value properties.

Finally, this is an older way of traversing a dictionary by pairs using KeyValuePair .

C# allows to loop over keys and values separetely.

The example prints all keys and all values of a dictionary in two foreach loops.

We use the Keys property to get all keys.

We use the Values property to get all values.

C# sort dictionary

We can use LINQ to sort dicionaries.

The example sorts the dictionary by user ages.

The OrderBy method is used to sort the entries by their values.

C# SortedDictionary

SortedDictionary represents a collection of key/value pairs that are sorted on the key.

The example demonstrates the usage of the SortedDictionary .

C# Dictionary of Lists

In the following example, we have a dictionary of lists.

We add three lists of integers into a dictionary. We compute a sum for each nested list and a final total sum.

Dictionary class - language reference

In this article we have worked with a C# Dictionary collection.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

assign to dictionary c#

C# - Dictionary<TKey, TValue>

The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no particular order.

Dictionary Characteristics

  • Dictionary<TKey, TValue> stores key-value pairs.
  • Comes under System.Collections.Generic namespace.
  • Implements IDictionary<TKey, TValue> interface.
  • Keys must be unique and cannot be null.
  • Values can be null or duplicate.
  • Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
  • Elements are stored as KeyValuePair<TKey, TValue> objects.

Creating a Dictionary

You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store. The following example shows how to create a dictionary and add key-value pairs.

In the above example, numberNames is a Dictionary<int, string> type dictionary, so it can store int keys and string values. In the same way, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionary cannot include duplicate or null keys, whereas values can be duplicated or null. Keys must be unique otherwise, it will throw a runtime exception.

Access Dictionary Elements

The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.

Update Dictionary

Update the value of a key by specifying a key in the indexer. It will throw the KeyNotFoundException if a key does not exist in the dictionary, therefore use the ContainsKey() method before accessing unknown keys.

Remove Elements in Dictionary

The Remove() method deletes an existing key-value pair from a dictionary. The Clear() method deletes all the elements of the dictionary.

Dictionary Class Hierarchy

The following diagram illustrates the generic Dictionary class hierarchy.

generic Dictionary C#

Learn about Dictionary methods and properties on docs.microsoft.com.

  • How to sort the generic SortedList in the descending order?
  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

Code Maze

  • Blazor WASM 🔥
  • ASP.NET Core Series
  • GraphQL ASP.NET Core
  • ASP.NET Core MVC Series
  • Testing ASP.NET Core Applications
  • EF Core Series
  • HttpClient with ASP.NET Core
  • Azure with ASP.NET Core
  • ASP.NET Core Identity Series
  • IdentityServer4, OAuth, OIDC Series
  • Angular with ASP.NET Core Identity
  • Blazor WebAssembly
  • .NET Collections
  • SOLID Principles in C#
  • ASP.NET Core Web API Best Practices
  • Top REST API Best Practices
  • Angular Development Best Practices
  • 10 Things You Should Avoid in Your ASP.NET Core Controllers
  • C# Back to Basics
  • C# Intermediate
  • Design Patterns in C#
  • Sorting Algorithms in C#
  • Docker Series
  • Angular Series
  • Angular Material Series
  • HTTP Series
  • .NET/C# Author
  • .NET/C# Editor
  • Our Editors
  • Leave Us a Review
  • Code Maze Reviews

Select Page

Dictionary in C#

Posted by Code Maze | Updated Date Jul 13, 2022 | 2

Dictionary in C#

In this article, we are going to talk about the Dictionary in C#. We will learn how to create a dictionary, add, retrieve, update, and delete elements. Among that, we will see the usage of its common properties and methods.

Let’s begin.

What Is Dictionary in C#?

Dictionary<TKey,TValue> is a generic collection that stores the data in key-value pairs. It implements IDictionary<TKey,TValue> interface.

In C# we don’t have a built-in Map type. But we can use Dictionary<TKey,TValue> to map objects. It is a useful tool that allows us to map value to a key.

A dictionary cannot have null or duplicate keys, whereas it can have null and duplicate values.

Become a patron at Patreon!

Now, let’s look at its implementation.

Create a Dictionary in C#

Let’s take a look at three ways to create a dictionary.

Initializing an Empty Dictionary

Let’s start by creating an empty dictionary:

var dict1 = new Dictionary<int, string>();

We create the dict1 dictionary with an empty constructor, and it doesn’t have any data. We do it this way if we want to create an empty dictionary.

Initializing With the Number of Elements

Another way we can initialize a dictionary is by setting the number of elements: 

var dict2 = new Dictionary<int, string>(10);

We can use this implementation if we want to define the initial capacity of our dictionary. If we know the number of elements we are going to store in our dictionary, it is always great for performance to define an initial capacity.

Initializing With Data

In addition, we can also populate the dictionary with some data:

We have seen how to create a dictionary.

Now, let’s dive in deeper and create a Dictionary<int, Product> that maps a Product value to a key. We will use this for the rest of our application.

That said, let’s inspect our Product class:

We will first create an empty productsDict dictionary:

var productsDict = new Dictionary<int, Product>();

Let’s carry on and look at how to add elements, fetch, update, and delete its elements.

Add Elements to a Dictionary in C#

We can add elements to productsDict by using the built-in Add(TKey,TValue) method:

After we execute the code, productsDict now has 3 <int, Product> key-value pairs as its elements.

Remember, we said a dictionary cannot have duplicate keys. Then, what happens if we add an element with a key that already exists? Yes, it will throw an exception.

So, we should always check whether the key we are trying to add is already added.

Let’s see a demonstration of facing this exception:

In our productDict dictionary, we already have a key with a value of 2. Therefore, it is not possible to add a Product as a value with the same key – we will come across an exception. 

In order to handle the exception, we wrap the Add(TKey,TValue) method with a try/catch block.

After we run our app, we can inspect the error message in the console window:

An item with the same key has already been added. Key: 2

To prevent this, without needing to use try/catch blocks, we can use the TryAdd(TKey,TValue) method:

This method attempts to add the element to the dictionary. It returns true if it can successfully add the element, or it returns false and skips the if statement without raising an exception.

When we add a new key value such as 3, the method returns true and then successfully adds the new Product to productsDict .

As a result, we see the console output:

Product is added.

Retrieve Elements From a Dictionary in C#

To retrieve elements from a dictionary in C#, we iterate through the dictionary and get them as KeyValuePair objects.

Here’s how we do it with a  foreach loop:

We iterate through each KeyValuePair in productsDict to fetch the mapped value. As a result, we obtain Product object with its ProductId and ProductName properties:

There are also other ways to iterate through a dictionary. If you want to learn about them, please check our article on Different Ways to Iterate Through a Dictionary in C# .

Thread Safety With Dictionary

There is something worthwhile to mention here. The dictionary supports multiple reads at the same time during the enumeration. However, it doesn’t give access to writing during the enumeration. This means it doesn’t allow multiple threads to operate reading and writing at the same time. Therefore, this is not a thread-safe procedure. To find out more information about thread safety, please take a look at the documentation on Thread Safety .

Retrieve an Element With a Given Key 

When we want to fetch a value of a specific key, we first need to check if the key exists in the dictionary. We can use several ways to do this.

ContainsKey(TKey) –  this method returns true or false depending on whether the key exists in the dictionary.

Also, there is another built-in method – TryGetValue(Tkey, TValue) :

This method safely returns the value if the given key exists without throwing an exception. It returns false if the key doesn’t exist. If the method finds a key, it sets the assigned value to the product1 variable by using the out keyword.

The console output as a result:

Key = 2 exists, Value = 113, TV

Check our article on How to Detect if a Dictionary Key Exists in C# that explains these methods in more detail. Also, we have an article on How to Get an Item by Index from Dictionary in C# that we recommend reading.

Retrieve an Element by Using an Extension Method

In addition to the previous methods, we are going to inspect one more method – GetValueOrDefault<TKey,TValue> . This is an extension method that comes with IDictionary<TKey,TValue> . As we mentioned before, Dictionary<TKey,TValue> inherits from the IDictionary<TKey,TValue> interface. Therefore, we can use the extension methods the interface provides.

GetValueOrDefault<TKey,TValue> takes the key and returns its value. In this case, we don’t need to use the out keyword. It returns the value automatically if it exists. Otherwise, it returns the default value:

We take 1 as the value of the key parameter we want to fetch from the dictionary. When we execute the code, because a key with a value of 1 exists, it returns the Product value that is mapped to it. 

We can see the output in the console window:

Key = 1 exists, Value = 112, Chair

Take a notice that we perform a null check. Especially when using reference types in the dictionary, we have to watch out for the possibility of obtaining null values. If the GrtValueOrDefault method can’t find the key in the dictionary, it would return null . As a result, we would face NullReferenceException . 

So, what is so special about this method, and why would we want to use it instead of the other methods such as TryGetValue<TKey,TValue> ?

Well, with this method, we can set a default value that we want to return if the key we request doesn’t exist:

We set a default value of "Color not found." . To emphasize, the type of the default value has to match TValue type we declared in the dictionary, which is a string in this case.

As the key with a value of 4 does not exist, we can see the default value as our result.

You can explore the List of Extension Methods we can use for different scenarios.

Update Dictionary in C#

Let’s carry on with our productsDict and see how to update its elements.

We can simply update the value of an element using the Item[Key] :

productsDict[0] = new Product() { ProductId = 110, ProductName = "Desk" };

With it, we can get or set the value of the element of the given key. Accordingly, the value of the key parameter 0 changes:

As a rule of thumb, we cannot retrieve, or update a value that doesn’t exist. As well as, we cannot add an element with a key that we already added. Therefore, we should also check if the key we want to update exists using the methods we discussed. 

Remove Dictionary Elements

There is another commonly used built-in method – Remove(TKey) . We use this method to remove a certain existing element:

productsDict.Remove(2);

After executing the method, the element with the key parameter value of 2 is not in the productDict anymore:

If we want to remove all the elements from a dictionary in C#, we also have a built-in Clear() method for that:

productsDict.Clear();

Let’s check if we successfully cleared the dictionary elements. In order to check this, we will use the property – Count :

This property shows us the number of elements in the dictionary.

In this case, we expect the number of elements to be 0:

Number of dictionary elements: 0

In this article, we have learned about Dictionary in C#.

We looked at creating and adding to a dictionary and how to retrieve, update, and remove its elements. We implemented commonly used methods and properties. We also covered some edge cases and ways to deal with exceptions.

guest

Thanks, this just clear and concise.

MarinkoSpasojevic

You are most welcome.

wpdiscuz

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Enumerable. To Dictionary Method

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Creates a Dictionary<TKey,TValue> from an IEnumerable<T> .

ToDictionary<TKey,TValue>(IEnumerable<ValueTuple<TKey,TValue>>, IEqualityComparer<TKey>)

Creates a dictionary from an enumeration according to specified key equality comparer.

Type Parameters

The type of the keys from elements of source .

The type of the values from elements of source .

The enumeration to create a dictionary from.

An equality comparer to compare keys.

A dictionary that contains keys and values from source .

source is a null reference.

source contains one or more duplicate keys.

If comparer is null , the default equality comparer Default is used to compare keys.

ToDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)

Creates a dictionary from an enumeration according to specified key comparer.

ToDictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)

Creates a dictionary from an enumeration according to the default comparer for the key type.

A dictionary that contains keys and values from source and uses the default comparer for the key type.

ToDictionary<TKey,TValue>(IEnumerable<ValueTuple<TKey,TValue>>)

A dictionary that contains keys and values from source and uses default comparer for the key type.

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to specified key selector and element selector functions.

The type of the elements of source .

The type of the key returned by keySelector .

The type of the value returned by elementSelector .

An IEnumerable<T> to create a Dictionary<TKey,TValue> from.

A function to extract a key from each element.

A transform function to produce a result element value from each element.

A Dictionary<TKey,TValue> that contains values of type TElement selected from the input sequence.

source or keySelector or elementSelector is null .

keySelector produces a key that is null .

keySelector produces duplicate keys for two elements.

The ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) method uses the default equality comparer Default to compare keys.

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function, a comparer, and an element selector function.

An IEqualityComparer<T> to compare keys.

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function.

A Dictionary<TKey,TValue> that contains keys and values. The values within each group are in the same order as in source .

source or keySelector is null .

The following code example demonstrates how to use ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) to create a Dictionary<TKey,TValue> by using a key selector.

The ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) method uses the default equality comparer Default to compare keys.

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function and key comparer.

The type of the keys returned by keySelector .

Was this page helpful?

Submit and view feedback for

Additional resources

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Add contents of a Dictionary to another Dictionary in C#

This post will discuss how to add the contents of a Dictionary to another Dictionary in C#. The solution should add key-value pairs present in the given dictionary into the source dictionary.

1. Using List<T>.ForEach() method

The idea is to convert the second dictionary into a List of KeyValuePair<K,V> Then, insert each entry into the first dictionary using the ForEach() method.

Download    Run Code

  The above code throws an ArgumentException when attempting to add a duplicate key.

To overwrite the value of a key already present in the dictionary, we can use dict[key] = value syntax instead of the Add() method. This is demonstrated below:

2. Using foreach loop

We can also iterate over the dictionary using a regular foreach loop and append all the second dictionary entries into the first dictionary. This solution handles duplicate keys as it uses the dict[key] property instead of the Add() method.

That’s all about adding contents of a Dictionary to another Dictionary in C#.

Initialize a Dictionary in C#
Add values to a Dictionary in C#
Get corresponding key from a given value in Dictionary in C#

Rate this post

Average rating 4.11 /5. Vote count: 9

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

assign to dictionary c#

Software Engineer | Content Writer | 12+ years experience

guest

  • 90% Refund @Courses
  • .NET Framework
  • C# Data Types
  • C# Keywords
  • C# Decision Making
  • C# Delegates
  • C# Constructors
  • C# ArrayList
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception

Related Articles

  • Solve Coding Problems

Introduction

  • C# Tutorial
  • Introduction to .NET Framework
  • C# | .NET Framework (Basic Architecture and Component Stack)
  • Hello World in C#
  • Common Language Runtime (CLR) in C#

Fundamentals

  • C# | Identifiers
  • C# | Data Types
  • C# | Variables
  • C# | Literals
  • C# | Operators
  • C# | Keywords

Control Statements

  • C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
  • Switch Statement in C#
  • Loops in C#
  • C# | Jump Statements (Break, Continue, Goto, Return and Throw)

OOP Concepts

  • C# | Class and Object
  • C# | Constructors
  • C# | Inheritance
  • C# | Encapsulation
  • C# | Abstraction
  • C# | Methods
  • C# | Method Overloading
  • C# | Method Parameters
  • C# | Method Overriding
  • Anonymous Method in C#
  • C# | Arrays
  • C# | Jagged Arrays
  • C# | Array Class
  • How to sort an Array in C# | Array.Sort() Method Set - 1
  • How to find the rank of an array in C#
  • ArrayList in C#
  • C# | ArrayList Class
  • C# | Array vs ArrayList
  • C# | String
  • C# | Verbatim String Literal - @
  • C# | String class
  • StringBuilder in C#
  • C# | String vs StringBuilder
  • C# | Tuple Class
  • ValueTuple in C#
  • ValueTuple Struct in C#
  • C# | Indexers
  • C# | Multidimensional Indexers
  • C# | Overloading of Indexers
  • C# | Properties
  • C# | Restrictions on Properties

Collections & Generics

  • Collections in C#
  • C# | Collection Class
  • C# | Generics - Introduction
  • List Implementation in C#
  • C# SortedList with Examples
  • HashSet in C# with Examples
  • SortedSet in C# with Examples

C# Dictionary with examples

  • SortedDictionary Implementation in C#
  • C# Hashtable with Examples
  • C# Stack with Examples
  • C# Queue with Examples
  • Linked List Implementation in C#

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable . The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need. Important Points:

  • IDictionary<TKey,TValue> Interface
  • IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface
  • IReadOnlyDictionary<TKey,TValue> Interface
  • IDictionary Interface
  • In Dictionary, the key cannot be null, but value can be.
  • In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception.
  • In Dictionary, you can only store same types of elements.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.

How to create the Dictionary?

Dictionary class has 7 constructors which are used to create the Dictionary, here we only use Dictionary<TKey, TValue>() constructor and if you want to learn more about constructors then refer C# | Dictionary Class . Dictionary<TKey, TValue>(): This constructor is used to create an 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 as follows: Step 1: IncludeSystem.Collections.Generic namespace in your program with the help of using keyword. Syntax:

Step 2: Create a Dictionary using Dictionary<TKey, TValue> class as shown below:

Step 3: If you want to add elements in your Dictionary then use Add() method to add key/value pairs in your Dictionary. And you can also add key/value pair in the dictionary without using Add method. As shown in the below example. Step 4: The key/value pair of the Dictionary is accessed using three different ways:

  • for loop: You can use for loop to access the key/value pairs of the Dictionary. Example:  
  • Using Index: You can access individual key/value pair of the Dictionary by using its index value. Here, you just specify the key in the index to get the value from the given dictionary, no need to specify the index. Indexer always takes the key as a parameter, if the given key is not available in the dictionary, then it gives KeyNotFoundException . Example:  
  • foreach loop: You can use foreach loop to access the key/value pairs of the dictionary.As shown in the below example we access the Dictionary using a foreach loop.

Example:  

How to remove elements from the Dictionary?

In Dictionary, you are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:

  • Clear : This method removes all keys and values from the Dictionary<TKey,TValue>.
  • Remove : This method removes the value with the specified key from the Dictionary<TKey,TValue>.

How to check the availability of elements in the Dictionary?

In Dictionary, you can check whether the given key or value present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods for checking and the methods are:

  • ContainsKey : This method is used to check whether the Dictionary<TKey,TValue> contains the specified key.
  • ContainsValue : This method is used to check whether the Dictionary<TKey,TValue> contains a specific value.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !

Please Login to comment...

author

  • CSharp Dictionary Class
  • CSharp-Generic-Namespace
  • karandeep1234
  • emilchirila97

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Dot Net Tutorials

LINQ ToDictionary Method in C#

Back to: LINQ Tutorial For Beginners and Professionals

LINQ ToDictionary Method in C# with Examples

In this article, I will discuss the LINQ ToDictionary Method in C# with Examples. Please read our previous article discussing the LINQ ToList and ToArray Methods in C# with Examples. Like the LINQ ToList and ToArray, the ToDictionary method also belongs to the conversion operator category.

LINQ ToDictionary Method in C#:

In C#, LINQ (Language Integrated Query) provides a set of methods for querying objects that implement IEnumerable<T>. One such method is ToDictionary, which converts a collection into a Dictionary<TKey, TValue> based on a key selector function and an optional element selector function.

The ToDictionary method in C# is a LINQ extension method that converts a sequence of elements (e.g., a collection or query result) into a dictionary. It is particularly useful when you have a collection of objects with key-value pairs, and we want to create a dictionary where the keys are derived from the elements in the collection.

The ToDictionary method is defined in the System.Linq namespace can create a dictionary from an enumerable collection where each element is transformed into a key-value pair. This method causes the query to be executed immediately. There are four overloaded versions available for this method. Let us start the discussion with the following overloaded version.

Parameters:

This method takes two parameters. They are as follows:

  • source : It is the Collections.Generic.IEnumerable<T> collection from which we need to create a System.Collections.Generic.Dictionary<TKey, TValue> collection.
  • keySelector : It is a function that is basically used to extract a key from each element.

Type Parameters:

  • TSource : The type of elements of the source sequence.
  • TKey : The type of the key returned by the key Selector.
  • It returns a System.Collections.Generic.Dictionary<TKey, TValue> collection that contains keys and values.

Exceptions:

This method throws the following two exceptions.

  • It throws ArgumentNullException when the source or keySelector is null  or the keySelector function produces a null key.
  • Throws ArgumentException when the keySelector produces duplicate keys for two elements.

Example to Convert a List to a Dictionary in C#.

Here, in the following example, the product ID is the key, and the Product is its value. 

When you run the above application, it will give the output as expected, as shown below.

ToDictionary Method in C# Output

Note: Keep in mind that if there are duplicate keys in the source collection, the ToDictionary method will throw an exception. You can handle this situation by providing a custom key selector or using the ToLookup method if duplicate keys are expected.

Another Overloaded Version of the ToDictionary Method in C#:

The following ToDictionary method Creates a System.Collections.Generic.Dictionary<TKey, TValue> collection from the System.Collections.Generic.IEnumerable<T> according to the specified key selector and element selector .

  • source: It is the source System.Collections.Generic.IEnumerable<T> collection from where we need to create a System.Collections.Generic.Dictionary<TKey, TValue>.
  • keySelector: A function to extract a key from each element.
  • elementSelector : A transform function to produce a result element value from each element.
  • TSource : The type of elements of source.
  • TElement : The type of value returned by the element selector.
  • It returns a System.Collections.Generic.Dictionary<TKey, TValue> that contains values of type TElement selected from the input sequence.
  • It throws System.ArgumentNullException when the source or key selector is null or the key selector function produces a null key.
  • It also throws System.ArgumentException when the key selector  produces duplicate keys for two elements.

Example to Understand the above LINQ ToDictionary Method in C#:

In the following example, we convert List<Product> to a Dictionary . Here, the product ID is the key, and the Product name is its value.

Linq ToDictionary Method in C# Output

What happens when the key is the same for two elements?

In the following example, it throws a System.ArgumentException as there are two products with the same ID (i.e., Products with id 1001), and we are using ID as the key for the dictionary.

Note: Remember that the keySelector must select unique keys, as dictionaries do not allow duplicate keys. If there are duplicates, ToDictionary will throw an ArgumentException. To handle duplicates, you could use a method like GroupBy before calling ToDictionary or handle the duplicates in a way that fits your specific requirements.

What happens when the source is null?

In the following example, it will throw System.ArgumentNullException as the source (i.e., listProducts) is null.

When to use the LINQ ToDictionary Method in C#?

You should use the ToDictionary method in C# when you have a collection of data, and you want to transform that data into a dictionary where you can easily look up values by their associated keys. Here are some scenarios when you might consider using the ToDictionary method:

Converting a Collection to a Dictionary:

When you have a collection of objects or elements, you need to organize them into a dictionary for efficient key-based access. var dictionary = collection.ToDictionary(keySelector);

Projecting Data:

When you want to transform a collection by projecting certain properties or values into keys and values in a dictionary. var dictionary = collection.ToDictionary(keySelector, valueSelector);

Grouping Data:

When you want to group elements from a collection into a dictionary based on a common property or key. var groupedDictionary = collection.GroupBy(keySelector).ToDictionary(group => group.Key, group => group.ToList());

Indexing Data for Quick Lookups:

When you have a collection of items and want to build an index to retrieve items by specific property or key efficiently. var itemIndex = collection.ToDictionary(item => item.KeyProperty);

Creating Dictionaries From Query Results:

When working with LINQ queries, you may want to convert query results into dictionaries for further processing or data manipulation. var result = dataContext.Customers           .Where(customer => customer.IsActive)           .ToDictionary(customer => customer.Id);

Merging or Aggregating Data:

When you want to merge data from multiple sources into a single dictionary, combine values based on a common key. var dictionary1 = source1.ToDictionary(keySelector); var dictionary2 = source2.ToDictionary(keySelector); var mergedDictionary = dictionary1.Concat(dictionary2) .ToDictionary(pair => pair.Key, pair => pair.Value);

When Not to Use LINQ ToDictionary Method in C#?

While the ToDictionary method in C# is a useful tool for converting collections or query results into dictionaries, there are situations where it may not be the best choice. Here are some scenarios in which you might want to avoid using ToDictionary:

  • Duplicate Keys: If the source collection or query result contains duplicate keys, using ToDictionary will throw an exception. In such cases, consider using the ToLookup method if you need to handle multiple values associated with the same key.
  • Modifying Existing Dictionary: If you have an existing dictionary that you want to modify, it’s often more efficient to directly add or update entries using the dictionary’s methods (Add, Remove, etc.) rather than creating a new dictionary with ToDictionary. Creating a new dictionary can be less efficient and consumes more memory.
  • Expensive Key or Value Transformations: If the key or value transformation logic provided to ToDictionary is computationally expensive or involves complex operations, repeatedly using ToDictionary in performance-critical scenarios may result in unnecessary overhead. In such cases, consider precomputing the dictionary or optimizing your code.
  • Deferred Execution Concerns: Be cautious when using ToDictionary with LINQ queries with deferred execution. The dictionary will be populated when the query is executed, not when ToDictionary is called. If the underlying data source changes between the time you call ToDictionary and the execution of the query, you may get unexpected results.
  • Memory Usage: Creating a dictionary consumes memory, and if you have a large collection, converting it to a dictionary can lead to increased memory usage. Be mindful of memory constraints, especially in scenarios where memory is limited.
  • Performance Considerations: In some cases, using a foreach loop or other techniques may be more performant than using LINQ methods like ToDictionary, especially for simple data transformations or when working with large datasets.
  • Simplicity: If you don’t need the key-value structure provided by a dictionary and are just iterating over the data or performing other operations, using ToDictionary might introduce unnecessary complexity to your code.

So, the ToDictionary method is useful whenever you need to convert data from a collection or query result into a key-value data structure for efficient lookups, grouping, or indexing purposes. It’s a powerful tool in LINQ that can simplify many data manipulation tasks in C#.

In the next article, I will discuss the need and use of the LINQ Cast Method in C# with Examples. Here, in this article, I try to explain the need and use of the LINQ ToDictionary Method in C# with Examples. I hope you enjoy this article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

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

MAKOLYTE

Solve real coding problems

C# – Convert a list to a dictionary

The simplest way to convert a list to a dictionary is to use the Linq ToDictionary() method:

This loops through the list and uses the key/element selector lambdas you passed in to build the dictionary.

In this article, I’ll go into details about how to use ToDictionary() and show how to deal with duplicate keys.

Note: I’m using named parameters – keySelector/elementSelector – for readability purposes.

Table of Contents

With a loop

The non-Linq way to convert a list to a dictionary is to use a loop:

This has slightly better performance than using Linq. I’d recommend using whichever approach you find easier to understand in your specific scenario.

Implicit element selector

These two statements produce the same result:

If you don’t specify the elementSelector, it will automatically use the items in the list as the elements. This is often what you want if you’re indexing objects by one of their properties.

How to handle duplicate keys

If the list has a duplicate key, ToDictionary() will throw ArgumentException: An item with the same key has already been added .

This is the same exception you get when you try to insert a duplicate key using Dictionary.Add(key, value) .

If you don’t expect your data to have duplicate keys, then throwing an exception is the right thing to do.

If it’s possible for your data to have duplicate keys, you’ll have to group by the key and decide what to use for the value. I’ll show three options below using Linq, and one example of how to solve this when you’re looping.

Option 1 – Select an aggregate value for the key

This example is calculating word counts. Words can repeat, so you have to group by the word and select the count as an aggregate value.

This outputs the following:

Option 2 – Select a list of elements for the key

This example is indexing movies by the year they were released. There can be multiple movies per year, and you want the movie objects, so you’ll need a dictionary of lists (Dictionary<int, List<Movie>>). To do this, you can select the group as a list.

This outputs:

Option 3 – Select first element with the key

When there are duplicate keys, sometimes you’ll want to select one of the items to represent the group. In the simplest scenario, you’d just select the first element in the group. This is the same as selecting distinct objects by a property .

For example, this is indexing movies by year and only selecting one movie for each year:

Dealing with duplicates when looping

If you’re looping instead of using Linq, you can deal with duplicates by checking if the key exists and choosing how to deal with the duplicates.

In this example, it’s creating a list of movies per year. When it sees the key doesn’t exist yet, it initializes it with an empty list, then adds the movie to the list.

To me, this is a bit easier to understand than the Linq-based approach (using GroupBy() + ToDictionary()).

Related Articles

  • C# – Convert a dictionary to a list
  • C# – Filter a dictionary
  • C# – Loop through a dictionary
  • C# – Get key with the max value in a dictionary
  • C# – Case insensitive dictionary

2 thoughts on “C# – Convert a list to a dictionary”

Thanks a lot for this article. Exactly what is needed!

I’m glad it helped you!

Leave a Comment Cancel reply

IMAGES

  1. C# Dictionary

    assign to dictionary c#

  2. C# Dictionary

    assign to dictionary c#

  3. C# Dictionary

    assign to dictionary c#

  4. Introduction to Dictionaries

    assign to dictionary c#

  5. Pointer to a dictionary in c#

    assign to dictionary c#

  6. C# object to dictionary

    assign to dictionary c#

VIDEO

  1. C# Collections :51 Generic Dictionary in Telugu

  2. Understanding CRUD operations on Dictionary in c# .NET Core 8

  3. C# Dictionary(Key, Value) Explained

  4. C#

  5. C#.net Part 49

  6. Java

COMMENTS

  1. c#

    And this is the Add method: public void Add (TKey key, TValue value) { this.Insert (key, value, true); } I won't post the entire Insert method as it's rather long, however the method declaration is this: private void Insert (TKey key, TValue value, bool add) And further down in the function, this happens:

  2. Proper way to initialize a C# dictionary with values

    With C# 6.0, you can create a dictionary in the following way: var dict = new Dictionary<string, int> { ["one"] = 1, ["two"] = 2, ["three"] = 3 }; It even works with custom types. ... Assign a different color to each face using geometry nodes Ambiguity of personal pronouns more hot questions ...

  3. How to initialize a dictionary with a collection initializer

    In this article. A Dictionary<TKey,TValue> contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value. One way to initialize a Dictionary<TKey,TValue>, or any collection whose Add method takes multiple parameters, is to enclose each set of parameters in braces as shown in the following example. . Another option is to use an index ...

  4. C# Dictionary

    We add two new pairs to the dictionary using dictionary access notation and the Add method. Console.WriteLine (string.Join (", ", users)); We use the string Join method to display all elements in one shot. users.Remove ("Jane Doe"); A pair is removed with the Remove method. The parameter is the dictionary key.

  5. Dictionary<TKey,TValue> Class (System.Collections.Generic)

    The capacity of a Dictionary<TKey,TValue> is the number of elements the Dictionary<TKey,TValue> can hold. As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array..NET Framework only: For very large Dictionary<TKey,TValue> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by ...

  6. C#

    The simplest way to add a key/value pair to a dictionary is by using Dictionary.Add(), like this:. using System.Collections.Generic; var dictionary = new Dictionary< string, int >(); dictionary.Add("Bob", 1); Code language: C# (cs). If the key already exists, Dictionary.Add() throws an ArgumentException because the key must be unique.. There are a few other ways to add to a dictionary in ...

  7. Dictionary<TKey,TValue>.Add (TKey, TValue) Method

    Examples. The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.. This code example is part of a larger example provided for the Dictionary<TKey,TValue> class. ...

  8. C# Dictionary Examples

    Dictionary. The C# Dictionary is a collection that we can use to map keys to values. Each key must have the same type (like string), and all values must have a type as well. ... Or we can assign the Dictionary variable to null. This causes little difference in memory usage—the entries are garbage-collected.

  9. C# Dictionary

    In the above example, numberNames is a Dictionary<int, string> type dictionary, so it can store int keys and string values. In the same way, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionary cannot include duplicate or null keys, whereas values can be duplicated or null. Keys must be unique otherwise, it will throw a runtime ...

  10. Add values to a Dictionary in C#

    This post will discuss how to add values to a Dictionary in C#. 1. Using Dictionary<TKey,TValue>.Add (TKey, TValue) method. The Dictionary.Add () method can be used to add the specified key and value to a dictionary. The following method demonstrates how to use the Add method for adding a new key-value pair to an existing dictionary.

  11. Dictionary in C#

    Retrieve Elements From a Dictionary in C#. To retrieve elements from a dictionary in C#, we iterate through the dictionary and get them as KeyValuePair objects. ... If the method finds a key, it sets the assigned value to the product1 variable by using the out keyword. The console output as a result:

  12. C#

    Courses. Practice. Dictionary<TKey,TValue>.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.

  13. Generic Dictionary Collection Class in C# with Examples

    Now, if you want to add elements i.e. a key/value pair into the Dictionary, then you need to use the following Add () method of the Generic Dictionary Collection Class in C#. Add (TKey key, TValue value): The Add (TKey key, TValue value) method is used to add an element with the specified key and value into the Dictionary.

  14. Enumerable.ToDictionary Method (System.Linq)

    Creates a dictionary from an enumeration according to the default comparer for the key type. ToDictionary<TSource,TKey,TElement> (IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to specified key selector and element selector functions.

  15. Add contents of a Dictionary to another Dictionary in C#

    The solution should add key-value pairs present in the given dictionary into the source dictionary. 1. Using List<T>.ForEach () method. The idea is to convert the second dictionary into a List of KeyValuePair<K,V> Then, insert each entry into the first dictionary using the ForEach () method. 1.

  16. C# Dictionary with examples

    In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is ...

  17. LINQ ToDictionary Method in C# with Examples

    Example to Understand the above LINQ ToDictionary Method in C#: In the following example, we convert List<Product> to a Dictionary. Here, the product ID is the key, and the Product name is its value. Dictionary<int, string> productsDictionary = listProducts.ToDictionary(x => x.ID, x => x.Name);

  18. C#

    The simplest way to convert a list to a dictionary is to use the Linq ToDictionary () method: using System.Linq; var movieList = GetMovieList (); var moviesById = movieList.ToDictionary (keySelector: m => m.Id, elementSelector: m => m); Code language: C# (cs) This loops through the list and uses the key/element selector lambdas you passed in to ...

  19. c#

    But you still cannot assign new references to your sb variables using the dictionary: d ["sb2"] = new StringBuilder ("Oh"); //sb2 is still and will always be null Console.Write (sb2.Length); //null reference exception. Using new here stops the dictionary pointing to sb2 and points it to something else, sb2 is not changed and is still null.