System.Linq.Enumerable Class
Provides a number of methods by calling the methods of an iterator object.
ToLookup Method
public static ILookup<TKey, TElement>
ToLookup<TSource, TKey, TElement>(
IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
)
Parameters
source: IEnumerable<TSource>
An IEnumerable<TSource> to group elements from.
keySelector: Func<TSource, TKey>
A function to extract each element's key.
elementSelector: Func<TSource, TElement>
A function to map each source element to an element in the resulting ILookup<TKey, TElement>.
Return Value
ILookup<TKey, TElement>
An ILookup<TKey, TElement> that contains elements of the input collection keyed by keySelector.
Description
Creates a Lookup<TKey, TElement> by applying a selector function to each element of the source collection. This operation is deferred.
An ILookup<TKey, TElement> is a collection of elements that are grouped by a key. Each key in the ILookup<TKey, TElement> has an associated collection of elements that share that key.
Examples
Basic Usage
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
var words = new[] {
"apple", "banana", "cherry", "apricot", "blueberry", "grape"
};
// Group words by the first letter and create a lookup
var lookupByFirstLetter = words.ToLookup(
word => word[0], // Key selector: the first character of the word
word => word // Element selector: the word itself
);
// Output the results
foreach (var group in lookupByFirstLetter)
{
Console.Write($"Key: '{group.Key}' - ");
Console.WriteLine(string.Join( ", ", group));
}
}
}
Output:
Key: 'a' - apple, apricot
Key: 'b' - banana, blueberry
Key: 'c' - cherry
Key: 'g' - grape
Using different element selector
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Group numbers by whether they are even or odd
var lookupByParity = numbers.ToLookup(
num => num % 2 == 0, // Key selector: true for even, false for odd
num => num.ToString() // Element selector: the number as a string
);
// Output the results
foreach (var group in lookupByParity)
{
if (group.Key)
{
Console.Write("Even numbers: ");
}
else
{
Console.Write("Odd numbers: ");
}
Console.WriteLine(string.Join( ", ", group));
}
}
}
Output:
Odd numbers: 1, 3, 5, 7, 9
Even numbers: 2, 4, 6, 8, 10