[LINQ Operators] ToDictionary

The “ToDictionary” operator creates a “Dictionary<K,T>” from a sequence.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “ToDictionary” operator

  • NonDeferred operator
  • Purpose: Conversion

 

3. Prototypes

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

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

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

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

Looks quite complex! Fear Not. Just focus the first one and the third one. The first syntax is with a key selector and the output element is the same element in a source collection. The third syntax allows you to provide the selector for an output element too.

 

4. Example 1 (Standard Operator) – Key Selector

var emps = Employee.GetEmployees();

Dictionary<string, Employee> empDictionary
  = emps.ToDictionary(k => k.Name);

foreach (KeyValuePair<string, Employee> e in empDictionary)
{
  Console.WriteLine("{0} : {1}, {2}", e.Key, e.Value.Id, e.Value.CityId);
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “ToDictionary()” operator.

 

6. Example 3 (Standard Operator) – Key Selector and Element Selector

IEnumerable<Employee> emps = Employee.GetEmployees();
IEnumerable<City> cities = City.GetCities();

var empsByCity
  = from c in cities     // outer sequence
    join e in emps    // inner sequence
    on c.Id equals e.CityId // keys
    select new { Employer = e.Name, City = c.Name };

Dictionary<string, string> empDictionary
  = empsByCity.ToDictionary(k => k.Employer, e => e.City);

foreach (KeyValuePair<string, string> e in empDictionary)
{
  Console.WriteLine("{0} : {1}", e.Key, e.Value);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s