Skip to content

ZH TW CSharp Keyword into

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: into

使用手冊C# · 實用指南

分組/選擇後繼續查詢或呼叫分組加入結果。

簡單範例 (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.Count();
System.Console.WriteLine(string.Join(",", result));

結果:

2,1

句法

group value by key into groupName ...

查詢在遍歷過程中通常以延遲的方式執行。 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