Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

group: practical reference

group: practical reference: group creates element groups by a key after by in a query expression.

Version: C# language; verified against C# 14 reference

Syntax

group /* grammar-specific form */

group creates element groups by a key after by in a query expression.

Use it for later aggregation, optionally continuing the query with into.

In LINQ-to-Objects grouping buffers the source; another provider may translate it differently.

null keys and comparer behavior depend on the operator or provider.

The complete program actually uses group; its exact expected stdout is a:2,b:1.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var query = from word in new[] { "ant", "ape", "bee" }
            group word by word[0] into words
            select $"{words.Key}:{words.Count()}";
Console.WriteLine(string.Join(",", query));

Result

a:2,b:1

The complete program actually uses `group`; its exact expected stdout is `a:2,b:1`.

Sources