CSharp - LINQ ToDictionary

Introduction

The ToDictionary operator creates a Dictionary of type <K, T> from an input sequence of type T.

K is the type of the key and T is the type of the stored values.

Prototypes

There are four prototypes we cover.

public static Dictionary<K, T> ToDictionary<T, K>(
  this IEnumerable<T> source,
  Func<T, K> keySelector);

In this prototype, a Dictionary of type <K, T> is created and returned by enumerating the input sequence named source.

The keySelector method delegate is called to extract the key value from each input element, and that key is the element's key into the Dictionary.

The second ToDictionary prototype accepts an IEqualityComparer<K> object. Here is the second prototype:

public static Dictionary<K, T> ToDictionary<T, K>(
  this IEnumerable<T> source,
        Func<T, K> keySelector,
        IEqualityComparer<K> comparer);

This prototype uses an IEqualityComparer<K> object to make comparisons on the key value.

So if you add or access an element in the Dictionary, it will use this comparer to compare the key to the keys already in the Dictionary.

The third ToDictionary prototype accepts an element selector so that the data type of the value stored in the Dictionary can be of a different type than the input sequence element.

public static Dictionary<K, E> ToDictionary<T, K, E>(
        this IEnumerable<T> source,
        Func<T, K> keySelector,
        Func<T, E> elementSelector);

The fourth prototype accepts an elementSelector and a comparer object.

public static Dictionary<K, E> ToDictionary<T, K, E>(
        this IEnumerable<T> source,
        Func<T, K> keySelector,
        Func<T, E> elementSelector,
        IEqualityComparer<K> comparer);

Exceptions

  • ArgumentNullException is thrown if the source, keySelector, or elementSelector argument is null or if a key returned by keySelector is null.
  • ArgumentException is thrown if a keySelector returns the same key for two elements.

The following code creates a dictionary of type Dictionary<int, Student> where the key of type int is the id member of the Student class and the Student object itself is the element stored.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from w w  w  .jav  a 2 s .c  o m*/
{
    static void Main(string[] args)
    {
        Dictionary<int, Student> eDictionary = Student.GetStudentsArray().ToDictionary(k => k.id);

        Student e = eDictionary[2];
        Console.WriteLine("Student whose id == 2 is {0} {1}", e.firstName, e.lastName);
    }
}
class Student
{
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student { id = 1, firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student { id = 2, firstName = "Windows", lastName = "Python" });
        al.Add(new Student { id = 3, firstName = "Application", lastName = "HTML" });
        al.Add(new Student { id = 4, firstName = "David", lastName = "Visual" });
        al.Add(new Student { id = 101, firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student[] GetStudentsArray()
    {
        return ((Student[])GetStudentsArrayList().ToArray());
    }
}

Result

We declare our Dictionary to have a key type of integer since we will be using the Student.id field as the key.

The Dictionary element type is Student as well.

Related Topics