C# ToDictionary: Set Keys and Values With Lambda

Use the ToDictionary extension from System.Linq to set keys and values with a lambda.
ToDictionary converts a collection into a Dictionary. It works on IEnumerable collections such as arrays and Lists. We can it to optimize performance—while retaining short and clear code. This method simplifies the demands of the code.DictionaryIEnumerable
First, this is an example of using the ToDictionary method in LINQ. We have built many Dictionary instances before. You simply loop over each element in your array and add it to the dictionary if it isn't already there.

Tip: LINQ gives us an extension method called ToDictionary, which can greatly simplify some code.

Important: The 2 arguments to ToDictionary are lambdas: the first sets each key, and the second sets each value.

Lambda: Look at the "v => v" style lines. Lambda can be expressed as "goes to," meaning each item in the array goes to itself.

C# program that uses ToDictionary using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example integer array. int[] values = new int[] { 1, 3, 5, 7 }; // First argument is the key, second the value. Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true); // Display all keys and values. foreach (KeyValuePair<int, bool> pair in dictionary) { Console.WriteLine(pair); } } } Output [1, True] [3, True] [5, True] [7, True]
Example 2. You can use this method with a List of strings. Dictionaries are most useful for strings and string lookups. This allows us to use a number (hash code) in place of a string, greatly speeding things up.

Also: Here we use the var keyword to simplify the syntax. This reduces repetitive syntax.

C# program that uses ToDictionary and List using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example with strings and List. List<string> list = new List<string>() { "cat", "dog", "animal" }; var animals = list.ToDictionary(x => x, x => true); if (animals.ContainsKey("dog")) { // This is in the Dictionary. Console.WriteLine("dog exists"); } } } Output dog exists
LINQ. The benefit of LINQ is that it allows us to use fewer lines of boilerplate code to insert elements into a Dictionary. This reduces lines of code and typos. It is elegant and fits well with other LINQ code.

Note: LINQ methods are significantly slower, but will scale equally well. Some programmers may not understand lambda syntax.


Caution: Sometimes, using ToDictionary may prevent you from combining the loop with another operation, also leading to inefficient code.

Summary. We used LINQ and the ToDictionary extension method to quickly transform one kind of collection such as an array or List into a Dictionary collection. This provides constant-time lookups.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls