Construct a Dictionary from a List of keys in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "C" }; Dictionary<string, int> dict = list.ToDictionary(x => x, x => 0); Console.WriteLine(String.Join(", ", dict)); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "A", "C" }; Dictionary<string, int> dict = list.Distinct().ToDictionary(x => x, x => 0); Console.WriteLine(String.Join(", ", dict)); } } |
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>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<string> list = new List<string>() { "A", "B", "A", "C" }; ILookup<string, int> lookup = list.ToLookup(x => x, x => x); foreach (IGrouping<string, int> group in lookup) { Console.WriteLine("{0}: {1}", group.Key, String.Join(", ", group)); } } } |
Output:
A: 0, 0
B: 0
C: 0
That’s all about constructing a Dictionary from a List of keys in C#.
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 :)