C# ToLookup

LINQ (language integrated query)

ToLookup returns a data structure that allows indexing. It is an extension method in the System.Linq namespace. It produces an ILookup instance can be indexed or enumerated using a foreach-loop. The entries are combined into groupings at each key.

This C# article shows how to use the ToLookup extension method from System.Linq.

Example

Note

First this example uses an input string array of three string elements. The ToLookup method receives a Func delegate, which is specified as a lambda expression. The implicit type syntax (var) is used on the result of the ToLookup method. Then, the key with value 3 and key with value 5 are accessed and the internal groupings are looped over. Finally, all groupings are accessed and enumerated programmatically.

Program that uses ToLookup method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Create an array of strings.
	string[] array = { "cat", "dog", "horse" };

	// Generate a lookup structure where the lookup is based on the key length.
	var lookup = array.ToLookup(item => item.Length);

	// Enumerate strings of length 3.
	foreach (string item in lookup[3])
	{
	    Console.WriteLine("3 = " + item);
	}

	// Enumerate strings of length 5.
	foreach (string item in lookup[5])
	{
	    Console.WriteLine("5 = " + item);
	}

	// Enumerate groupings.
	foreach (var grouping in lookup)
	{
	    Console.WriteLine("Grouping:");
	    foreach (string item in grouping)
	    {
		Console.WriteLine(item);
	    }
	}
    }
}

Output

3 = cat
3 = dog
5 = horse
Grouping:
cat
dog
Grouping:
horse
Lambda expression syntax

Description. In the C# language, a lambda expression is a procedure specified in a different syntax: the formal parameters are specified on the left side of the => token, while the method body is specified on the right side. The lambda expression in this example specifies that the lookup value for each string is the string's length. Therefore, a string such as "cat" will have a lookup value of 3.

ToDictionary

Programming tip

Let's compare the ToLookup method to the ToDictionary method. The Dictionary data structure requires that only one key be associated with one value. The ToLookup data structure, however, is more lenient in that it allows one key to be associated with multiple values, as shown in the example above.

ToDictionary Method

Summary

The C# programming language

We saw the ToLookup extension method in the System.Linq namespace and applied in the context of a program that uses string lengths to access strings. This method is useful when you want to create a Dictionary-type data structure using LINQ but do not want to enforce a single key-value mapping strategy—the lookup data structure created allows multiple values on a single key.

LINQ Examples
.NET