C# Group By Operator

LINQ (language integrated query)

You have a query expression and want it to return the results as groups. With the group by operators in the C# language, you can separate the results of an expression into groups, as we demonstrate in this example.

Example

Note

The group by clause comes at the end of a query expression; no select clause is required in query expressions that use group by. The first part of group by indicates what item is to be grouped, and after the by operator, you specify the condition that results in groups. Here, IsEven returns true or false for every number; some numbers are grouped in the "false" category and the rest are grouped in the "true" category.

Odd and Even Numbers

This C# program uses the group keyword in a query expression.

Program that uses group by operators [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 = 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

Using result. Probably the hardest part of using group by is knowing how to access its results. First, you can use foreach to enumerate the groups themselves. On each group, you can access the Key property. Finally, when you use foreach to enumerator on the group, you can get the values.

Foreach Loop Examples

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 in your program. It can be useful for creating sitemaps or other tree-like hiearchies.

LINQ Examples
.NET