
You want to transform your collection into groups that each have a key. With the GroupBy method from the System.Linq namespace, you can do this in your C# program on many collections. We examine the GroupBy method on a collection of numbers.
We are using the method syntax available in the System.Linq namespace. We call GroupBy with the argument being a lambda expression. Each element is identified as 'a' in the lambda expression (a => IsEven(a)). Then, the key becomes the result of IsEven, which is a boolean value. Thus the result is two groups with the keys True and False.
Program that uses GroupBy method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Input array.
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Group elements by IsEven.
var result = array.GroupBy(a => IsEven(a));
// Loop over groups.
foreach (var group in result)
{
// Display key for group.
Console.WriteLine("IsEven = {0}:", group.Key);
// Display values in group.
foreach (var value in group)
{
Console.Write("{0} ", value);
}
// End line.
Console.WriteLine();
}
}
static bool IsEven(int value)
{
return value % 2 == 0;
}
}
Output
IsEven = False:
1 3 5 7 9
IsEven = True:
2 4 6 8Notes. The group with the key of value False contains all the odd numbers. The group with the key of value True, meanwhile, contains all the even numbers.

Using the GroupBy method (or the equivalent query syntax keywords) is fine for certain parts of programs. However, if you are generating a collection that will be used repeatedly after creating it, it would probably be better to use ToDictionary instead. While GroupBy can index elements by keys, a Dictionary can do this and also has the performance advantages provided by hashing.
Group By Operator ToDictionary MethodIf each group contains multiple elements as is typical with GroupBy, you could use a List as the value of the Dictionary instance. Thus you would have a Dictionary of Lists.
Dictionary Examples List Examples
We looked at the GroupBy extension method in the C# programming language. Further, we discussed how the GroupBy method can be used in away similar to a Dictionary of Lists and noted the possible performance drawbacks.
LINQ Examples