GroupBy. This method transforms a collection into groups. Each group has a key. With this method from the System.Linq namespace, you can apply grouping to many collections.
Some usage notes. The GroupBy method can be used in away similar to a Dictionary of Lists. As with other LINQ methods, GroupBy has possible performance drawbacks.
Example. We call GroupBy with the argument being a lambda expression. Each element is identified as "a" in the lambda expression in the example program.
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.
Result The group with the key of value False contains the odds. And the group with the key of value True, meanwhile, contains the evens.
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;
}
}IsEven = False:
1 3 5 7 9
IsEven = True:
2 4 6 8
Discussion. Using GroupBy() is fine for certain parts of programs. However, if you are generating a collection that will be repeatedly used, it would be better to use ToDictionary.
And While GroupBy can index elements by keys, a Dictionary can do this and has the performance advantages provided by hashing.
Collection notes. If 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.
A summary. We looked at the GroupBy extension method in the C# programming language. This is effective in dividing up a collection of elements.
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 Nov 17, 2021 (edit link).