ES CSharp Keyword by - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
C#: by
Separa el valor del elemento de la clave en el grupo... por....
Ejemplo sencillo (Example.cs)
Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.
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));
Resultado:
1,0
Sintaxis
group value by key
La consulta generalmente se ejecuta con retraso durante el recorrido. ToArray/ToList captura el resultado en una nueva colección.
Ejemplo 1: forma básica
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}");
}
}
Ejemplo 2: otra forma práctica
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}");
}
}
Fuente oficial: Microsoft Aprender.