Skip to content

CSharp Operator Collection Expression

Codex edited this page Oct 11, 2026 · 2 revisions

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

Колекції та spread

Довідник C# · Практичне керівництво

Collection expression потребує цільового типу; spread додає елементи іншої послідовності. Не слід плутати spread із range.

Простий приклад (Example.cs)

Збережіть цей приклад окремо як Example.cs. Запускайте його незалежно від інших прикладів на сторінці.

Example.cs:

// PROJECT-EXAMPLE
int[] first = [1, 2];
int[] all = [.. first, 3];
System.Console.WriteLine(string.Join(",", all));

Результат:

1,2,3

Синтаксис

int[] values = [1, ..other, 5];

Приклад 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[] middle = [2, 3];
        int[] values = [1, ..middle, 4];
        Console.WriteLine(string.Join(",", values));
    }
}

Приклад 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)
    {
        List<string> names = ["ore", "wood"];
        List<string> all = [..names, "food"];
        Console.WriteLine(all.Count);
    }
}

Офіційне джерело: Microsoft Learn.

Clone this wiki locally