AYUDA .NET

C# para cada uno (Cómo funcionan las TI para desarrolladores)

Actualizado mayo 16, a. m.
Compartir:

En este tutorial, trataremos el bucle "foreach" de C#, una herramienta esencial para los desarrolladores. El bucle foreach simplifica el proceso de iteración a través de una colección, facilitando la realización de operaciones sobre cada elemento sin preocuparse de los detalles subyacentes. Discutiremos la importancia de foreach, sus casos de uso y cómo implementarlo en tu código C#.

Introducción al bucle `foreach

El bucle foreach es una potente herramienta para que los desarrolladores iteren a través de colecciones de forma concisa y legible. Simplifica el código y reduce las posibilidades de error, ya que no es necesario gestionar manualmente el índice o el recuento de los elementos de la colección. En términos de declaraciones de variables, el bucle foreach tiene cinco declaraciones de variables, mientras que el bucle for sólo tiene tres declaraciones de variables.

Los casos de uso de foreach incluyen:

  • Suma de valores en una colección
  • Buscar un artículo en una colección
  • Modificar elementos de una colección
  • Realizar acciones en cada elemento de una colección

Comprender las colecciones

Existen diferentes tipos de colecciones en C# que se utilizan para almacenar un grupo de elementos en un único objeto. Se trata de matrices, listas, diccionarios, etc. El bucle foreach es una herramienta útil que se puede utilizar con cualquier colección que implemente la interfaz IEnumerable o IEnumerable.

Algunos tipos de recogida habituales son:

  • Matrices: Una colección de tamaño fijo de elementos con el mismo tipo de datos.
  • Listas: Una colección dinámica de elementos con el mismo tipo de datos.
  • Diccionarios: Una colección de pares clave-valor, donde cada clave es única.

    El espacio de nombres System.Collections.Generic contiene el método de extensión ForEach que puede utilizarse con cualquier clase de colección incorporada.

Implementación de la sentencia foreach en C#

Ahora que tenemos una comprensión básica de las colecciones y el bucle for each, vamos a sumergirnos en la sintaxis y ver cómo funciona en C#.

Sintaxis del bucle For Each

    foreach (variableType variableName in collection)
    {
        // Code to execute for each item
    }
    foreach (variableType variableName in collection)
    {
        // Code to execute for each item
    }
For Each variableName As variableType In collection
		' Code to execute for each item
Next variableName
VB   C#

Aquí, variableType representa el tipo de datos de los elementos de la colección, variableName es el nombre dado al elemento actual en el bucle (variable de bucle)y collection se refiere a la colección sobre la que se quiere iterar.

Ejemplo

Consideremos un ejemplo en el que tenemos una lista de números enteros y queremos hallar la suma de todos los elementos de la lista.

    using System;
    using System.Collections.Generic;
            // Create a list of integers
            List numbers = new List { 1, 2, 3, 4, 5 };
            // Initialize a variable to store the sum
            int sum = 0;
            // Iterate through the list using for each loop
            foreach (int number in numbers)
            {
                sum += number;
            }
            // Print the sum
            Console.WriteLine("The sum of the elements is: " + sum);
    using System;
    using System.Collections.Generic;
            // Create a list of integers
            List numbers = new List { 1, 2, 3, 4, 5 };
            // Initialize a variable to store the sum
            int sum = 0;
            // Iterate through the list using for each loop
            foreach (int number in numbers)
            {
                sum += number;
            }
            // Print the sum
            Console.WriteLine("The sum of the elements is: " + sum);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Salida

Cuando el bucle se ejecuta, da la siguiente salida.

    The sum of the elements is: 15
    The sum of the elements is: 15
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'The sum @of the elements is: 15
VB   C#

En el ejemplo anterior, primero creamos una lista de enteros llamada números e inicializamos una variable suma para almacenar la suma de los elementos. A continuación, utilizamos el bucle foreach para recorrer la lista y añadir el valor de cada elemento a la suma. Por último, imprimimos la suma en la consola. También podemos imprimir un array utilizando el bucle foreach de forma similar.

Variaciones y buenas prácticas

Ahora que tenemos una comprensión básica de cómo utilizar el bucle for each, vamos a discutir algunas variaciones y mejores prácticas.

Iteración de sólo lectura: El bucle for each es el más adecuado para la iteración de sólo lectura, ya que modificar la colección mientras se itera puede provocar resultados inesperados o errores en tiempo de ejecución. Si necesita modificar la colección durante la iteración, considere utilizar un bucle for tradicional o crear una nueva colección con las modificaciones deseadas.

Utilizar la palabra clave var: En lugar de especificar explícitamente el tipo de datos de los elementos de la colección, puedes utilizar la palabra clave var para dejar que el compilador infiera el tipo de datos. Esto puede hacer que el código sea más conciso y fácil de mantener.

Ejemplo:

    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }
    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }
For Each number In numbers
		Console.WriteLine(number)
Next number
VB   C#

**Cuando utilices un bucle for each para iterar a través de diccionarios, necesitarás trabajar con la estructura KeyValuePair. Esta estructura representa un par clave-valor en un diccionario.

Ejemplo:

    Dictionary ageDictionary = new Dictionary
    {
        { "Alice", 30 },
        { "Bob", 25 },
        { "Charlie", 22 }
    };
    foreach (KeyValuePair entry in ageDictionary)
    {
        Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
    }
    Dictionary ageDictionary = new Dictionary
    {
        { "Alice", 30 },
        { "Bob", 25 },
        { "Charlie", 22 }
    };
    foreach (KeyValuePair entry in ageDictionary)
    {
        Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

LINQ y para cada uno: LINQ (Idioma Consulta integrada) es una potente función de C# que permite consultar y manipular datos de forma más declarativa. Puede utilizar LINQ con el bucle for each para crear un código más expresivo y eficiente.

Ejemplo:

    using System;
    using System.Collections.Generic;
    using System.Linq;
            List numbers = new List { 1, 2, 3, 4, 5 };
            // Use LINQ to filter out even numbers
            var evenNumbers = numbers.Where(n => n % 2 == 0);
            // Iterate through the even numbers using for each loop
            foreach (var number in evenNumbers)
            {
                Console.WriteLine(number);
            }
    using System;
    using System.Collections.Generic;
    using System.Linq;
            List numbers = new List { 1, 2, 3, 4, 5 };
            // Use LINQ to filter out even numbers
            var evenNumbers = numbers.Where(n => n % 2 == 0);
            // Iterate through the even numbers using for each loop
            foreach (var number in evenNumbers)
            {
                Console.WriteLine(number);
            }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Añadir funcionalidad IronPDF al tutorial de C# para cada uno

En esta sección, ampliaremos nuestro tutorial sobre el bucle "C# for each" presentando IronPDF, una popular biblioteca para trabajar con archivos PDF en C#. Demostraremos cómo utilizar el bucle foreach junto con IronPDF para generar un informe PDF basado en una colección de datos.

Presentación de IronPDF

IronPDF es una potente biblioteca para crear, editar y extraer contenido de archivos PDF en C#. Proporciona una API fácil de usar para trabajar con documentos PDF, lo que la convierte en una opción excelente para los desarrolladores que necesitan incorporar funciones PDF a sus aplicaciones.

Algunas de las principales características de IronPDF son:

  • Generar PDF a partir de HTMLURL e imágenes
  • Editar documentos PDF existentes
  • Extraer texto e imágenes de PDF
  • Añadir anotaciones, campos de formulario y cifrado a los PDF

Instalación de IronPDF

Para empezar a utilizar IronPDF, deberá instalar el paquete IronPDF NuGet. Puede hacerlo ejecutando el siguiente comando en el directorio de su proyecto:

Install-Package IronPdf

Generación de un informe PDF con IronPDF y para cada

En este ejemplo, utilizaremos la librería IronPDF y el bucle for each para crear un informe PDF de una lista de productos, incluyendo sus nombres y precios.

En primer lugar, vamos a crear una simple clase Producto para representar los productos:

    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
    }
    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }
    }
Public Class Product
		Public Property Name() As String
		Public Property Price() As Decimal
		Public Sub New(ByVal name As String, ByVal price As Decimal)
			Me.Name = name
			Me.Price = price
		End Sub
End Class
VB   C#

A continuación, vamos a crear una lista de objetos Producto para generar el informe PDF:

    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };
    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };
Dim products As New List From {
	New Product("Product A", 29.99D),
	New Product("Product B", 49.99D),
	New Product("Product C", 19.99D)
}
VB   C#

Ahora, podemos utilizar IronPDF y el bucle for each para generar un informe PDF que contenga la información del producto:

    using System;
    using System.Collections.Generic;
    using IronPdf;
    // Create a list of products
    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };
    // Initialize an HTML string to store the report content
    string htmlReport = "Product ReportNamePrice";
    // Iterate through the list of products using for each loop
    foreach (var product in products)
    {
        // Add product information to the HTML report
        htmlReport += $"{product.Name}${product.Price}";
    }
    // Close the table tag in the HTML report
    htmlReport += "";
    // Create a new instance of the HtmlToPdf class
    var htmlToPdf = new ChromePdfRenderer();
    // Generate the PDF from the HTML report
    var PDF = htmlToPdf.RenderHtmlAsPdf(htmlReport);
    // Save the PDF to a file
    PDF.SaveAs("ProductReport.PDF");
    // Inform the user that the PDF has been generated
    Console.WriteLine("ProductReport.PDF has been generated.");
    using System;
    using System.Collections.Generic;
    using IronPdf;
    // Create a list of products
    List products = new List
    {
        new Product("Product A", 29.99m),
        new Product("Product B", 49.99m),
        new Product("Product C", 19.99m),
    };
    // Initialize an HTML string to store the report content
    string htmlReport = "Product ReportNamePrice";
    // Iterate through the list of products using for each loop
    foreach (var product in products)
    {
        // Add product information to the HTML report
        htmlReport += $"{product.Name}${product.Price}";
    }
    // Close the table tag in the HTML report
    htmlReport += "";
    // Create a new instance of the HtmlToPdf class
    var htmlToPdf = new ChromePdfRenderer();
    // Generate the PDF from the HTML report
    var PDF = htmlToPdf.RenderHtmlAsPdf(htmlReport);
    // Save the PDF to a file
    PDF.SaveAs("ProductReport.PDF");
    // Inform the user that the PDF has been generated
    Console.WriteLine("ProductReport.PDF has been generated.");
Imports System
	Imports System.Collections.Generic
	Imports IronPdf
	' Create a list of products
	Private products As New List From {
		New Product("Product A", 29.99D),
		New Product("Product B", 49.99D),
		New Product("Product C", 19.99D)
	}
	' Initialize an HTML string to store the report content
	Private htmlReport As String = "Product ReportNamePrice"
	' Iterate through the list of products using for each loop
	For Each product In products
		' Add product information to the HTML report
		htmlReport &= $"{product.Name}${product.Price}"
	Next product
	' Close the table tag in the HTML report
	htmlReport &= ""
	' Create a new instance of the HtmlToPdf class
	Dim htmlToPdf = New ChromePdfRenderer()
	' Generate the PDF from the HTML report
	Dim PDF = htmlToPdf.RenderHtmlAsPdf(htmlReport)
	' Save the PDF to a file
	PDF.SaveAs("ProductReport.PDF")
	' Inform the user that the PDF has been generated
	Console.WriteLine("ProductReport.PDF has been generated.")
VB   C#

C# For Each (Cómo funciona para los desarrolladores) Figura 1 - Resultado de salida

Conclusión

A lo largo de este tutorial, hemos explorado los fundamentos del bucle "for each" de C#, su importancia, casos de uso y cómo implementarlo en tu código. También presentamos IronPDF, una potente biblioteca para trabajar con archivos PDF en C#, y demostramos cómo utilizar el bucle for each junto con IronPDF para generar un informe PDF basado en una colección de datos.

Sigue aprendiendo y desarrollando tus habilidades, y pronto serás capaz de aprovechar todo el potencial del bucle for each y otras características de C# para crear aplicaciones robustas y eficientes. IronPDF ofrece prueba gratuita para probar la biblioteca. Si decide comprarla, la licencia de IronPDF comienza a partir de $749.

< ANTERIOR
C# String Replace (Cómo funciona para desarrolladores)
SIGUIENTE >
Try/Catch en C# (Cómo funciona para desarrolladores)

¿Listo para empezar? Versión: 2024.8 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,439,034 Ver licencias >