Skip to content

KO CSharp Keyword group

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: group

핸드북 C# · 실용 가이드

IGrouping<TKey,TElement>에서 키별로 요소를 그룹화합니다.

간단한 예제 (Example.cs)

이 예제를 Example.cs로 따로 저장하고 이 페이지의 다른 예제와 독립적으로 실행하세요.

Example.cs:

// PROJECT-EXAMPLE
using System.Linq;
int[] values = [1, 2, 3];
var result = from n in values group n by n % 2 into groups select groups.Key;
System.Console.WriteLine(string.Join(",", result));

결과:

1,0

통사론

group value by key

쿼리는 일반적으로 순회 중에 지연된 방식으로 실행됩니다. ToArray/ToList는 새 컬렉션에 결과를 캡처합니다.

예시 1: 기본 형태

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        int[] values = [1, 2, 3, 4, 5];
        var query = from value in values
                    let parity = value % 2
                    group value by parity into grouped
                    where grouped.Any()
                    orderby grouped.Key ascending
                    select new { Key = grouped.Key, Total = grouped.Sum() };
        foreach (var item in query) Console.WriteLine($"{item.Key}:{item.Total}");
    }
}

예 2: 또 다른 실제 형식

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        string[] names = ["ore", "oak", "wood"];
        var query = from name in names
                    group name by name[0] into grouped
                    orderby grouped.Key descending
                    select new { Letter = grouped.Key, Names = string.Join(",", grouped) };
        foreach (var item in query) Console.WriteLine($"{item.Letter}:{item.Names}");
    }
}

공식 출처: Microsoft 학습.

Clone this wiki locally