This post will discuss how to construct a Dictionary from a List of keys in C#.

1. Using Enumerable.ToDictionary() Method

We can make use of the built-in method ToDictionary() from the System.Linq namespace to create a Dictionary<TKey,TValue> from a List<T>. The following code example creates a dictionary having keys from the list and corresponding values initialized with 0.

Download  Run Code

Output:

[A, 0], [B, 0], [C, 0]

 
If your list contains duplicate keys, call the Distinct() method on the list to remove duplicates, before invoking the ToDictionary() method.

Download  Run Code

Output:

[A, 0], [B, 0], [C, 0]

2. Using Enumerable.ToLookup() Method

If the elements of the list could be repeated, you can also use ToLookup instead. It allows multiple values per key. The following code example uses the ToLookup() method to create a generic Lookup<TKey,TElement> from a List<T>.

Download  Run Code

Output:

A: 0, 0
B: 0
C: 0

That’s all about constructing a Dictionary from a List of keys in C#.