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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 17, 2021 (edit link).