LINQ ToDictionary Query Operator

By Peter Bromberg

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. Here we see how LINQ simplifies the demands of your code, both for the machine and for you. An example of this method in the C# language.

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]

LINQ ToDictionary Query Operator  (957 Views)