Pruebe en producción sin marcas de agua.
Funciona donde lo necesite.
Obtén 30 días de producto totalmente funcional.
Ténlo en funcionamiento en minutos.
Acceso completo a nuestro equipo de asistencia técnica durante la prueba del producto
En este tutorial, trataremos el bucle "foreach" de C#, una herramienta esencial para los desarrolladores. El bucle foreach
simplifica el proceso de iterar a través de una colección, facilitando la realización de operaciones en cada elemento sin preocuparse por los detalles subyacentes. Hablaremos sobre la importancia de foreach
, sus casos de uso, y cómo implementarlo en tu código C#.
foreach
El bucle foreach
es una herramienta poderosa para los desarrolladores para iterar a través de colecciones de manera 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 solo tiene tres declaraciones de variables.
Los casos de uso para foreach
incluyen:
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 usar con cualquier colección que implemente la interfaz IEnumerable o IEnumerable.
Algunos tipos de recogida habituales son:
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 se puede usar con cualquier clase de colección integrada.
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#.
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
Aquí, variableType
representa el tipo de dato de los elementos en 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 que deseas iterar.
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<int> numbers = new List<int> { 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<int> numbers = new List<int> { 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
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
En el ejemplo anterior, primero creamos una lista de enteros llamada numbers
e inicializamos una variable sum 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.
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 solo de lectura: El bucle for each es más adecuado para iteraciones de solo lectura, ya que modificar la colección mientras se itera puede llevar a 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.
Uso de la palabra clave var: En lugar de especificar explícitamente el tipo de datos de los elementos en la colección, puedes usar la palabra clave var
para 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
Iteración a través de diccionarios: Al utilizar 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<string, int> ageDictionary = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 },
{ "Charlie", 22 }
};
foreach (KeyValuePair<string, int> entry in ageDictionary)
{
Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}
Dictionary<string, int> ageDictionary = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 },
{ "Charlie", 22 }
};
foreach (KeyValuePair<string, int> entry in ageDictionary)
{
Console.WriteLine($"{entry.Key} is {entry.Value} years old.");
}
Dim ageDictionary As New Dictionary(Of String, Integer) From {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 22}
}
For Each entry As KeyValuePair(Of String, Integer) In ageDictionary
Console.WriteLine($"{entry.Key} is {entry.Value} years old.")
Next entry
LINQ y foreach: LINQ (Language Integrated Query) es una característica poderosa en C# que te permite consultar y manipular datos de manera más declarativa. Puede usar 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<int> numbers = new List<int> { 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<int> numbers = new List<int> { 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);
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Private numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
' Use LINQ to filter out even numbers
Private evenNumbers = numbers.Where(Function(n) n Mod 2 = 0)
' Iterate through the even numbers using for each loop
For Each number In evenNumbers
Console.WriteLine(number)
Next number
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.
Documentación de 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:
Para empezar a utilizar IronPDF, deberá instalar el paquete IronPDF NuGet. Puedes hacer esto siguiendo las instrucciones en Instalación de IronPDF.
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.
Primero, creemos una clase Product simple 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
A continuación, vamos a crear una lista de objetos Product para generar el informe PDF:
List<Product> products = new List<Product>
{
new Product("Product A", 29.99m),
new Product("Product B", 49.99m),
new Product("Product C", 19.99m),
};
List<Product> products = new List<Product>
{
new Product("Product A", 29.99m),
new Product("Product B", 49.99m),
new Product("Product C", 19.99m),
};
Dim products As New List(Of Product) From {
New Product("Product A", 29.99D),
New Product("Product B", 49.99D),
New Product("Product C", 19.99D)
}
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<Product> products = new List<Product>
{
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 = "<table><tr><th>Product Name</th><th>Price</th></tr>";
// Iterate through the list of products using for each loop
foreach (var product in products)
{
// Add product information to the HTML report
htmlReport += $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>";
}
// Close the table tag in the HTML report
htmlReport += "</table>";
// 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<Product> products = new List<Product>
{
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 = "<table><tr><th>Product Name</th><th>Price</th></tr>";
// Iterate through the list of products using for each loop
foreach (var product in products)
{
// Add product information to the HTML report
htmlReport += $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>";
}
// Close the table tag in the HTML report
htmlReport += "</table>";
// 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(Of Product) 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 = "<table><tr><th>Product Name</th><th>Price</th></tr>"
' Iterate through the list of products using for each loop
For Each product In products
' Add product information to the HTML report
htmlReport &= $"<tr><td>{product.Name}</td><td>${product.Price}</td></tr>"
Next product
' Close the table tag in the HTML report
htmlReport &= "</table>"
' 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.")
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 una prueba gratuita para probar la biblioteca. Si decides comprarlo, la licencia de IronPDF comienza desde $749.