Home
C#
group Operator
Updated Mar 6, 2022
Dot Net Perls
Group by. In C# a query expression can return its results as a group. With the group-by operator, we separate the results of an expression into parts.
Useful. This syntax makes some query expressions in C# programs more useful. The group-by clause comes at the end of a query expression. No select clause is required.
GroupJoin
GroupBy
Example. With group by, 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
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; } }
False 1 3 5 7 9 True 2 4 6 8
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. The foreach-loop evaluates IEnumerables.
foreach
A 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.
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 Mar 6, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen