C# GroupBy

Data

GroupBy transforms a collection into groups. Each group has a key. With this 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.

Example

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)).

Lambda Expression

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.

C# program that uses GroupBy method

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 8

Results:The group with the key of value False contains the odds. And the group with the key of value True, meanwhile, contains the evens.

Discussion

Dictionary

Using the GroupBy method (or the equivalent query) is fine for certain parts of programs. However, if you are generating a collection that will be repeatedly used, it would probably be better to use ToDictionary instead.

And:While GroupBy can index elements by keys, a Dictionary can do this and has the performance advantages provided by hashing.

Group ByToDictionary

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. This is an efficient design.

DictionaryList

Summary

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.


C#: LINQ