Dot Net Perls

ToDictionary Use - C#

by Sam Allen

Problem

Transform an array or List into a Dictionary that contains a key for each element. Use ToDictionary from LINQ to optimize performance while retaining short and clear code. Use functional programming to simplify the demands of your code, both for the machine and for you.

Solution: C#

As C# developers, we have built many Dictionary objects 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.

How does it work?

ToDictionary performs the same operations as looping over each element and inserting it. Be aware, however, that it can be somewhat slower because of LINQ overhead. Here we use ToDictionary to create a lookup hash for an array of ints.

//
// 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)
{
    Debug.WriteLine(pair.Key.ToString() + ": " + pair.Value.ToString());
}
// Results:
// 1: True
// 3: True
// 5: True
// 7: True

Use it with 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.

//
// 2.
// 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.
    //
    Debug.WriteLine("dog exists");
}

Discussion

Pros of ToDictionary. 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.

Dot Net Perls
About
Sitemap
Source code
RSS
Dictionary
Dictionary Keys and Values
Dictionary Lookup Methods
Sort Dictionary Values
Dictionary vs. List Lookup Time
ToDictionary Use
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.