Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Group-By Operator

This C# program uses the group keyword in a query expression. It includes System.Linq.

Group by. A query expression can return its results as a group.

With the group-by operator, we separate the results of an expression into parts. This makes some query expressions more useful.

Example. 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, Even

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.
	    foreach (var value in group)

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



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.


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.

Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf