Saltar al pie de página
.NET AYUDA

Colección C# (Cómo Funciona para Desarrolladores)

C# has become a popular and adaptable option for developers among the many available programming languages. The concept of collections is at the core of C#'s extensive library and frameworks, which are one of the language's main advantages. In C#, a collection is essential for effectively storing and organizing data. They give developers a wide range of effective tools to solve challenging programming problems. We'll delve further into collections in this post, covering their features, types, and optimal usage strategies.

How to use C# Collections

  1. Create a new Console App project.
  2. Create an object for the collection in C#.
  3. Add the values to the collection class, which can store multiple sets of objects.
  4. Process the value operations like add, remove, sort, etc.
  5. Display the result and dispose of the object.

C#: Understanding Collections

Collections in C# are containers that let programmers work with and store sets of object classes. These objects are flexible and adaptable to many programming environments, and they might be of the same or distinct kinds. Most collection classes implement components of the System namespace in C#, meaning importing namespaces such as System.Collections and System.Collections.Generic, which offers various collection classes that are both generic and non-generic. Collections also allow for dynamic memory allocation, adding, searching, and sorting items within the collection classes.

Non-Generic Collection Types

ArrayList, Hashtable, and Queue are a few of the non-generic collection classes available in C# that were included in the first iterations of the language. These collections offer an alternative to explicitly defining the types of things you want to keep and work with. However, developers frequently choose generic collections because of their superior performance and type safety.

Generic Collections

Later iterations of C# included generic collections to overcome the drawbacks of non-generic collections. They provide type safety during compilation and let developers deal with tightly typed data. The generic collection classes List, Dictionary<TKey, TValue>, Queue, and Stack are a few that are often used. These collections are the go-to option in contemporary C# development because they provide better performance and compile-time type verification.

Key C# Collection Types

1. List

A dynamic array that facilitates quick and easy element insertion and removal is the List class. It is a flexible option for situations requiring a resizable collection since it offers ways to filter, search, and manipulate components.

// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
' Creating a list with integers and adding/removing elements
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
numbers.Add(6) ' Adds element '6' to the end
numbers.Remove(3) ' Removes the first occurrence of the element '3'
$vbLabelText   $csharpLabel

2. Dictionary<TKey, TValue>

With quick lookup speeds, a collection of key-value pairs is represented by the Dictionary<TKey, TValue> class. It is frequently employed in situations where having rapid access to data via a unique key value is crucial. This key is used to access elements within the dictionary.

// Creating a dictionary mapping names to ages
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // The string "John" is the key that can access the value 25
ageMap["Jane"] = 30; // Setting the key "Jane" to hold the value 30
// Creating a dictionary mapping names to ages
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // The string "John" is the key that can access the value 25
ageMap["Jane"] = 30; // Setting the key "Jane" to hold the value 30
' Creating a dictionary mapping names to ages
Dim ageMap As New Dictionary(Of String, Integer)()
ageMap.Add("John", 25) ' The string "John" is the key that can access the value 25
ageMap("Jane") = 30 ' Setting the key "Jane" to hold the value 30
$vbLabelText   $csharpLabel

3. Queue and Stack

The first-in, first-out collection (FIFO), and last-in, first-out (LIFO) paradigms are implemented, respectively, by the generic Queue and generic Stack classes. They can be used to manage items in a certain sequence based on the application's needs.

// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>(); 
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");

// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>(); 
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");

// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
' Creating and manipulating a queue
Dim tasks As New Queue(Of String)()
tasks.Enqueue("Task 1") ' Adding to the queue
tasks.Enqueue("Task 2")

' Creating and manipulating a stack
Dim numbers As New Stack(Of Double)()
numbers.Push(3.14) ' Adding to the stack
numbers.Push(2.71)
$vbLabelText   $csharpLabel

4. HashSet

Unique items arranged in an unordered collection are represented by the HashSet class. It offers effective ways to perform set operations such as difference, union, and intersection.

// Creating hashsets and performing a union operation
HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // Combining setA and setB
// Creating hashsets and performing a union operation
HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // Combining setA and setB
' Creating hashsets and performing a union operation
Dim setA As New HashSet(Of Integer) From {1, 2, 3, 4}
Dim setB As New HashSet(Of Integer) From {3, 4, 5, 6}
Dim unionSet As New HashSet(Of Integer)(setA)
unionSet.UnionWith(setB) ' Combining setA and setB
$vbLabelText   $csharpLabel

IronPDF

C# Collection (How It Works For Developers): Figure 1 - IronPDF website page

A C# library called IronPDF makes it easy to create, edit, and display PDF documents in .NET applications. It offers many licensing choices, cross-platform compatibility, high-quality rendering, and HTML to PDF conversion. IronPDF's user-friendly API makes handling PDFs easier, making it a valuable tool for C# developers.

The standout feature of IronPDF is its HTML to PDF conversion capability, which maintains all layouts and styles. It generates PDFs from web content, making it perfect for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be converted to PDFs effortlessly.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Key features of IronPDF include:

  • Convert HTML to PDF: With IronPDF, programmers may create PDF documents from HTML text, including CSS and JavaScript. This is especially useful for those who are already familiar with web development tools and wish to use HTML and CSS to create PDFs.
  • PDF Generation and Manipulation: The library provides the ability to create PDF documents from scratch programmatically. Additionally, it facilitates the editing of pre-existing PDFs, enabling operations like text extraction, watermark addition, split PDFs, and more.
  • Superior Rendering: IronPDF uses a rendering engine to generate PDF output of the highest caliber, ensuring that the final documents retain clarity and visual integrity.
  • Cross-Platform Compatibility: IronPDF is designed to function with both the .NET Core and .NET Framework, allowing it to be used in various applications and on a range of platforms.
  • Performance Optimization: Even when working with big or complicated PDF documents, the library is designed to provide efficient PDF production and rendering.

To know more about the IronPDF documentation, refer to the IronPDF Documentation.

Installation of IronPDF

Install the IronPDF library first using the Package Manager Console or NuGet Package Manager with:

Install-Package IronPdf

C# Collection (How It Works For Developers): Figure 2 - Installing IronPDF with the Package Manager Console

Using the NuGet Package Manager to search for the package "IronPDF" is an additional option. We may choose and download the necessary package from this list out of all the NuGet packages associated with IronPDF.

C# Collection (How It Works For Developers): Figure 3 - Installing IronPDF with the NuGet Package Manager

Document Creation with Collections using IronPDF

Understanding the role that collections play in data structures and organization is crucial before we dive into the interface with IronPDF. Developers may store, retrieve, and modify groupings of things in an organized manner by using collections. With so many different types available, such as List, Dictionary<TKey, TValue>, and HashSet, developers may select the collection that best fits their requirements.

Imagine that you have to create a report with a list of sales transactions in it. The data may be effectively organized using a List, which serves as a basis for additional processing and display.

// Define the Transaction class
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}

// Create a list of transactions
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
// Define the Transaction class
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}

// Create a list of transactions
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
' Define the Transaction class
Public Class Transaction
	Public Property ProductName() As String
	Public Property Amount() As Decimal
	Public Property [Date]() As DateTime
End Class

' Create a list of transactions
Private transactions As New List(Of Transaction) From {
	New Transaction With {
		.ProductName = "Product A",
		.Amount = 100.50D,
		.Date = DateTime.Now.AddDays(-2)
	},
	New Transaction With {
		.ProductName = "Product B",
		.Amount = 75.20D,
		.Date = DateTime.Now.AddDays(-1)
	}
}
$vbLabelText   $csharpLabel

In the PDF, we'll make a straightforward table that lists the product name, transaction amount, and date for each.

using IronPdf;

// Create a PDF document renderer
var pdfDocument = new HtmlToPdf();

// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";

// Convert HTML to PDF
PdfDocument pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);

// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
using IronPdf;

// Create a PDF document renderer
var pdfDocument = new HtmlToPdf();

// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";

// Convert HTML to PDF
PdfDocument pdf = pdfDocument.RenderHtmlAsPdf(htmlContent);

// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
Imports IronPdf

' Create a PDF document renderer
Private pdfDocument = New HtmlToPdf()

' HTML content with a table populated by data from the 'transactions' list
Private htmlContent As String = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>"
For Each transaction In transactions
	htmlContent &= $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>"
Next transaction
htmlContent &= "</table>"

' Convert HTML to PDF
Dim pdf As PdfDocument = pdfDocument.RenderHtmlAsPdf(htmlContent)

' Specify the file path to save the PDF
Dim pdfFilePath As String = "transactions_report.pdf"
pdf.SaveAs(pdfFilePath)
$vbLabelText   $csharpLabel

Developers have the option to save the PDF document to disk or show it to users once it has been produced. IronPDF offers several output choices, including browser streaming, file saving, and cloud storage integration.

C# Collection (How It Works For Developers): Figure 4 - Outputted PDF from the previous code

The above screen shows the output generated from the above code. To learn more about the code, refer to Using HTML to Create a PDF Example.

Conclusion

A plethora of opportunities for dynamic document production are made possible by combining collections with IronPDF. Developers may effectively manage and organize data by utilizing collections, and IronPDF makes it easy to create visually beautiful PDF documents. The combined power of IronPDF and collections offers a reliable and adaptable solution for dynamic content production in C# applications, regardless of the kind of document you're producing—invoices, reports, or anything else.

IronPDF's $799 Lite edition includes a year of software support, upgrade options, and a permanent license. Users also get the opportunity to evaluate the product in real-world circumstances during the watermarked trial period. To learn more about IronPDF's cost, licensing, and free trial, kindly visit the IronPDF Licensing Information. For more information on Iron Software, go to the Iron Software Website.

Preguntas Frecuentes

¿Qué son las colecciones en C# y por qué son importantes?

Las colecciones en C# son esenciales para el almacenamiento y organización de datos, proporcionando a los desarrolladores herramientas para manejar eficientemente desafíos de programación complejos. Permiten la asignación dinámica de memoria y una fácil manipulación de conjuntos de datos.

¿Cuáles son las diferencias entre las colecciones no genéricas y genéricas en C#?

Las colecciones no genéricas, como ArrayList y Hashtable, son menos seguras en tipos y pueden almacenar cualquier tipo de objeto. Las colecciones genéricas, como List y Dictionary, proporcionan seguridad de tipos y un rendimiento mejorado al asegurar la consistencia del tipo de datos.

¿Cómo se crea una lista genérica en C#?

Una lista genérica en C# se puede crear usando la clase List. Por ejemplo, una lista de enteros se puede crear con List numbers = new List { 1, 2, 3 };.

¿Cómo puedo convertir HTML a PDF en C#?

Puede usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas HTML en documentos PDF. También admite la conversión de archivos HTML y URL en documentos PDF, manteniendo la integridad del diseño y el estilo.

¿Cuáles son algunas mejores prácticas para usar colecciones en C#?

Las mejores prácticas para usar colecciones en C# incluyen elegir el tipo de colección adecuado para sus necesidades, como usar Dictionary para pares clave-valor y List para listas ordenadas, y asegurar una gestión adecuada de la memoria al desechar las colecciones cuando ya no se necesitan.

¿Cómo pueden las colecciones mejorar la creación de PDFs en aplicaciones C#?

Las colecciones pueden organizar eficientemente los datos para la creación de documentos. Por ejemplo, usar una List para compilar datos de ventas puede facilitar la generación de reportes PDF completos usando IronPDF, simplificando la gestión y presentación de datos.

¿Qué opciones de licencia están disponibles para IronPDF?

IronPDF ofrece una licencia Lite con un año de soporte y actualizaciones, y una versión de prueba con marca de agua para evaluación. Estas opciones permiten a los desarrolladores probar e implementar las capacidades de IronPDF en sus proyectos.

¿Cómo puedo instalar IronPDF en un proyecto .NET?

Puede instalar IronPDF en un proyecto .NET usando el Administrador de Paquetes NuGet con el comando Install-Package IronPdf. Alternativamente, puede buscar 'IronPDF' en el Administrador de Paquetes NuGet para añadirlo a su proyecto.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más