ToLookup. This returns a data structure that allows indexing. It is an extension method. We get an ILookup instance that can be indexed or enumerated using a foreach-loop.
Grouping notes. The entries are combined into groupings at each key. Duplicate keys are allowed—this is an important difference between ToLookup and ToDictionary.
First, this example uses an input string array of 3 string elements. The ToLookup method receives a Func delegate. This is specified as a lambda expression.
Then The key with value 3 and key with value 5 are accessed. The groupings are looped over. All groupings are accessed and enumerated.
Note The lambda expression in this example specifies that the lookup value for each string is the string's length.
Detail With this lambda expression, a string such as "cat" will have a lookup value of 3.
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);
}
}
}
}3 = cat
3 = dog
5 = horse
Grouping:
cat
dog
Grouping:
horse
Lambda notes. A lambda expression is a procedure. The formal parameters are specified on the left side of the arrow, while the method body is specified on the right side.
ToDictionary. The Dictionary data structure requires that only one key be associated with one value. The ToLookup data structure, however, allows one key to be associated with multiple values.
Summary. We saw the ToLookup extension method in the System.Linq namespace. This method is useful when you want to create a Dictionary-type data structure using LINQ.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (edit).