Skip to content

CSharp Keyword let

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: let

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

Обчислює проміжне значення для кожного елемента LINQ-запиту та дає йому ім’я.

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

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

Example.cs:

// PROJECT-EXAMPLE
using System.Linq;
int[] values = [1, 2, 3];
var result = from n in values let doubled = n * 2 select doubled;
System.Console.WriteLine(string.Join(",", result));

Результат:

2,4,6

Синтаксис

let name = expression

Запит зазвичай виконується відкладено під час перебору. 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)
    {
        var items = new[] { new { Id = 1, Name = "ore" }, new { Id = 2, Name = "wood" } };
        var counts = new[] { new { Id = 1, Count = 4 }, new { Id = 2, Count = 2 } };
        var query = from item in items
                    join count in counts on item.Id equals count.Id
                    let total = count.Count * 2
                    where total > 3
                    orderby total descending, item.Name ascending
                    select new { item.Name, Total = total };
        foreach (var item in query) Console.WriteLine($"{item.Name}:{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)
    {
        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}");
    }
}

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

Clone this wiki locally