C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
String LengthTherefore: With this lambda expression, a string such as "cat" will have a lookup value of 3.
C# program that uses ToLookup method
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