C# Group By

LINQ: language integrated query

A query expression can return the results as groups. With the group by operators in the C# language, we separate the results of an expression into groups. This makes some query expressions more effective.

Example

Note

The group by clause comes at the end of a query expression. No select clause is required. The first part indicates what item is to be grouped. And after "by", you specify the condition that results in groups.

Next:IsEven returns true or false. Some numbers are grouped in the "false" category. The rest are grouped in the "true" category.

Odd and Even Numbers
C# program that uses group by operators

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 = from element in array
		     orderby element
		     group element by IsEven(element);

	// Loop over groups.
	foreach (var group in result)
	{
	    // Display key and its values.
	    Console.WriteLine(group.Key);
	    foreach (var value in group)
	    {
		Console.WriteLine(value);
	    }
	}
    }

    static bool IsEven(int value)
    {
	return value % 2 == 0;
    }
}

Output

False
1
3
5
7
9
True
2
4
6
8
Foreach loop construct

With group, we must know how to access its results. First, we use foreach to enumerate the groups themselves. On each group, we access the Key property. Finally, when we use foreach on the enumerator of the group, we get the values.

Tip:More information on the foreach-loop, which evaluates IEnumerable, is available on this site.

Foreach

Summary

The group by clause is an alternative to the select clause in query expressions. It allows you to divide the results in any number of categories, which can simplify further logic. It can be useful for creating tree-like hierarchies.


C#: LINQ