Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de C#
C#
Getting Started with CSyntax BasicsTypes and DataProjects and PackagesErrors and TestingKey Concepts: LINQ, Delegates, and Async
Debates

Guía de C# · 6/6

Key Concepts: LINQ, Delegates, and Async

Por ahora, este capítulo solo está disponible en inglés.

Three features give C# much of its character: delegates and lambdas for passing functions as values, LINQ for declarative queries, and async/await for waiting on I/O without tying up a thread. Each builds on the one before it.

Delegates and Lambdas

A delegate is a type-safe reference to a method. You can declare your own delegate types, but most code uses the built-in Func<...> (returns a value) and Action<...> (returns nothing). A lambda expression, (parameters) => expression, creates an anonymous method on the spot.

Func<int, int, int> add = (a, b) => a + b;
Func<string, bool> isLong = s => s.Length > 5;
Action<string> log = message => Console.WriteLine($"[log] {message}");

Console.WriteLine(add(2, 3));          // 5
Console.WriteLine(isLong("TASTEDEV")); // True
log("starting up");

// a method that takes another function as an argument
static List<int> Apply(List<int> items, Func<int, int> transform)
{
    var result = new List<int>();
    foreach (var item in items)
        result.Add(transform(item));
    return result;
}

var doubled = Apply([1, 2, 3], x => x * 2); // [2, 4, 6]

// lambdas can capture variables from the surrounding scope
int threshold = 10;
Func<int, bool> overThreshold = x => x > threshold;

Events build on delegates too: button.Click += (sender, e) => ... attaches a lambda to an event.

LINQ

LINQ (Language Integrated Query) gives you one consistent way to query arrays, lists, databases, and other data sources. The most common style is method syntax: chaining extension methods from System.Linq and passing lambdas to them.

List<Order> orders =
[
    new("Ana", "Books", 18.00m),
    new("Ben", "Electronics", 320.00m),
    new("Ana", "Electronics", 45.00m),
    new("Cai", "Books", 22.00m),
];

var bigOrders = orders
    .Where(o => o.Amount >= 20m)
    .OrderByDescending(o => o.Amount)
    .Select(o => $"{o.Customer}: {o.Amount:F2}")
    .ToList();

var byCategory = orders
    .GroupBy(o => o.Category)
    .Select(g => new { Category = g.Key, Total = g.Sum(o => o.Amount), Count = g.Count() });

foreach (var row in byCategory)
    Console.WriteLine($"{row.Category}: {row.Count} orders, {row.Total:F2} total");

bool anyExpensive = orders.Any(o => o.Amount > 100m);
var first = orders.FirstOrDefault(o => o.Customer == "Cai");

record Order(string Customer, string Category, decimal Amount);

(With top-level statements, type declarations go last.) Query syntax reads more like SQL and compiles to the same method calls:

var query =
    from o in orders
    where o.Category == "Books"
    orderby o.Amount
    select o.Customer;

LINQ uses deferred execution: Where and Select only describe a query, which runs when you enumerate it or call , , or . Enumerating twice runs it twice, so call once if you will reuse the results.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorErrors and Testing
ToList
Count
First
ToList()

async/await and Task

File, network, and database operations spend most of their time waiting. An async method hands its thread back at each await while the operation is in flight, then resumes on the next line once it completes. Async methods return Task when they produce no value and Task<T> when they do.

using var http = new HttpClient();

static async Task<int> GetLengthAsync(HttpClient client, string url, CancellationToken token)
{
    string body = await client.GetStringAsync(url, token);
    return body.Length;
}

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

try
{
    // await one operation at a time
    int length = await GetLengthAsync(http, "https://learn.microsoft.com", cts.Token);
    Console.WriteLine($"Length: {length}");

    // start several operations at once and wait for all of them
    string[] urls = ["https://dotnet.microsoft.com", "https://www.nuget.org"];
    int[] lengths = await Task.WhenAll(urls.Select(u => GetLengthAsync(http, u, cts.Token)));
    Console.WriteLine(string.Join(", ", lengths));
}
catch (OperationCanceledException)
{
    Console.WriteLine("Timed out, so the requests were cancelled.");
}

Top-level statements can use await directly. A handful of rules will keep you out of most async trouble:

  • Give async methods an Async suffix and have them return Task or Task<T>.
  • Reserve async void for event handlers, because callers cannot catch its exceptions.
  • Don't block on async work with .Result or .Wait(); await all the way up. Blocking is a classic cause of deadlocks.
  • Accept a CancellationToken in long-running operations so they can be stopped.
  • Run independent operations concurrently with Task.WhenAll.

Reuse HttpClient instead of creating one per request; web apps usually get clients from IHttpClientFactory.

Summary

  • Func and Action delegates hold lambdas, letting you pass behavior as a value; lambdas can capture surrounding variables.
  • LINQ chains operators like Where, Select, GroupBy, and OrderBy to work with data declaratively, and it runs only when results are needed.
  • async/await with Task keeps threads free while waiting, and CancellationToken makes long operations cancellable.

Further Reading

  • C# documentation: the official language tour, tutorials, and language reference.
  • .NET documentation: guides to the runtime, libraries, and the dotnet CLI.
  • LINQ overview: query syntax and the standard query operators in depth.
  • Asynchronous programming: the async/await model and task-based patterns.
  • .NET API browser: look up any type or member in the base class libraries.
  • NuGet Gallery: search public packages and review their details.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.