Dot Net Perls

ToDictionary Method in C#

by Sam Allen - Updated June 13, 2009

Problem. You want to transform the elements in an array or List into a Dictionary instance. Use ToDictionary from LINQ to optimize performance while retaining short and clear code. Solution. Here we see how LINQ simplifies the demands of your code, both for the machine and for you. We look at an example of this method in the C# language.

1. Using ToDictionary

First, we look at a simple 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. LINQ gives us an extension method called ToDictionary, which can greatly simplify some code.

=== Program that uses ToDictionary (C#) ===

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
        };

        //
        // 1.
        // 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 of the program ===

[1, True]
[3, True]
[5, True]
[7, True]

ToDictionary has two arguments. There is a single argument and a two argument version of ToDictionary. The first argument uses lambda expressions to set the key, and the second for values. The Dictionary used here is an int Dictionary. [C# Array and Dictionary Test, Integer Lookups - dotnetperls.com]

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

2. Using ToDictionary with strings

Here we look at how 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. Here we use the var keyword to simplify the syntax. [C# Var Examples - dotnetperls.com]

=== Program that uses ToDictionary and List (C#) ===

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 of the program ===

dog exists

3. Understanding LINQ

The benefits 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's elegant and fits well with other LINQ code.

Negatives. LINQ methods are significantly slower, but will scale equally well. Many programmers may not understand lambda syntax (although they should learn). Sometimes, using ToDictionary may prevent you from combining the loop with another operation, also leading to inefficient code.

4. Summary

Here we looked at how you can use LINQ and the ToDictionary extension method to quickly transform one kind of collection such as an array or List into a Dictionary collection, which provides constant-time lookups. This is useful in some cases where performance is not critical and short code is more important.

Dot Net Perls
LINQ | Enumerable.Range | Lazy Evaluation | Sum Method | Var Examples | XElement Example
C# | Dictionary StringComparer Tip | DateTime.TryParse Example | Reflection Field Example | Validate Characters in String
© 2009 Sam Allen. All rights reserved.