.NET HELP

C# Collection (How It Works For Developers)

Published March 6, 2024
Share:

Introduction

C# has become a popular and adaptable option for developers among the many available programming languages. The idea 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, it 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 settings, and they might be of the same or distinct kinds. Most collection classes implement components of the System in C#, this means 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 the items on 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 sorts 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 Stackare 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 Listclass. It is a flexible option for situations requiring a resizable collection since it offers ways to filter, search, and manipulate components.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
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 all the items that are '3'
VB   C#

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 special key value is crucial. This key is used to access elements within the dictionary.

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
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
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
VB   C#

3. Queueand Stack

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

Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Dim tasks As New Queue(Of String)() ' creating a queue class
tasks.Enqueue("Task 1") ' adding to the queue
tasks.Enqueue("Task 2")
Dim numbers As New Stack(Of Double)() ' creating a stack class
numbers.Push(3.14) ' adding to the stack
numbers.Push(2.71)
VB   C#

4. HashSet

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

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
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
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
VB   C#

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, which makes it a useful tool for C# developers.

The standout feature of IronPDF is its HTML to PDF capability, maintaining 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
VB   C#

Key features of IronPDF include:

  • Convert HTML to PDF: With IronPDF, programmers may create PDF documents from HTML text, including CSS and JavaScript. Those who are already familiar with web development tools and wish to use HTML and CSS to create PDFs will find this very helpful.
  • PDF Generation and Manipulation: The library offers 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, guaranteeing that the final documents retain clarity and visual integrity.
  • Cross-Platform Compatibility: IronPDF may be used in a variety of applications and on a range of platforms because it is made to function with both the.NET Core and.NET Framework.
  • Performance Optimisation: 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 here.

Installation of IronPDF

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

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 choice. 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 go 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.

public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
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
};
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
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
};
Public Class Transaction
	Public Property ProductName() As String
	Public Property Amount() As Decimal
	Public Property [Date]() As DateTime
End Class
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)
	}
}
VB   C#

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

var pdfDocument = new IronPdf.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);
pdf.SaveAs(pdfFilePath);
var pdfDocument = new IronPdf.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);
pdf.SaveAs(pdfFilePath);
Dim pdfDocument = New IronPdf.HtmlToPdf()
' HTML content with a table populated by data from the 'transactions' list
Dim 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)
pdf.SaveAs(pdfFilePath)
VB   C#

Developers have the option to save the PDF document to the 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 here.

Conclusion

A plethora of opportunities for dynamic document production are made possible by the combination of 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 $749 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 license page. For more information on Iron Software, go to this website.

< PREVIOUS
MSTest C# (How It Works For Developers )
NEXT >
C# Null Conditional Operator (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >