.NET HELP

C# Enumerable (How it Works for Developers)

Published January 14, 2025
Share:

Introduction

C#'s IEnumerable interface is one of the most versatile tools in the .NET framework, enabling developers to work with collections in a highly flexible manner. When combined with IronPDF, IEnumerable allows for dynamic data manipulation and efficient PDF generation, making it ideal for scenarios like creating reports, exporting data, or generating documents from database queries.

Using IEnumerable ensures that your application remains scalable and memory-efficient, as it processes data lazily and avoids loading entire datasets into memory at once. This is especially useful for large-scale applications handling extensive collections of data, such as a massive database table.

What is IronPDF?

C# Enumerable (How it Works for Developers): Figure 1

IronPDF is a powerful .NET library designed to simplify the process of creating, editing, and managing PDF files programmatically. It offers a wide range of features, including HTML to PDF conversion, text extraction, PDF merging, and more. By integrating IronPDF into your C# projects, you can efficiently handle complex PDF tasks without needing deep expertise in PDF internals.

IronPDF also supports a variety of formats, allowing you to generate PDFs from raw HTML, Razor Views, ASP.NET web pages, or even directly from data structures. This flexibility makes it an essential tool for developers building modern, data-driven applications.

Getting Started

Installing IronPDF

To use IronPDF in your project, follow these steps:

Via NuGet Package Manager Console

  1. Open your .NET project in Visual Studio.

    1. Open the NuGet Package Manager Console under the tools dropdown.

C# Enumerable (How it Works for Developers): Figure 2

  1. Run the following command:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

Via NuGet Package Manager for Solution

  1. Within your Visual Studio Project, go to tools > NuGet Package Manager > Manage NuGet Packages for Solution

    1. Search for IronPDF

C# Enumerable (How it Works for Developers): Figure 3

  1. Click "Install" to begin installing the IronPDF package into your project

C# Enumerable (How it Works for Developers): Figure 4

Basic Concepts of Enumerable in C#

The IEnumerable interface represents a sequence of elements that can be enumerated. Common examples include arrays, lists, and LINQ query results. By leveraging LINQ, you can filter, sort, and project data into the desired format before generating PDFs with IronPDF.

One of the key advantages of IEnumerable is its deferred execution model, which allows queries to be executed only when their results are accessed. This enables efficient data manipulation and reduces the computational overhead in complex workflows.

Additionally, the list implements IEnumerable means that any collection like Listcan be treated as an IEnumerable, enabling easy LINQ operations, filtering, and transformation.

Practical Use Cases

Generating PDFs from Enumerable Data

Example: Exporting a List of Objects to a PDF Table

Imagine you have a list that implements IEnumerable of employees that you need to export as a PDF table. Using IEnumerable and IronPDF, you can iterator method iterate through the data and convert it into a well-structured PDF.

To enhance the presentation, you can use HTML tables with inline CSS to style the rows and columns dynamically based on the data. This ensures that the PDF output is both functional and visually appealing.

Filtering and Transforming Data Before PDF Generation

Example: Using LINQ to Select and Format Data

With LINQ, you can filter and transform your data before passing it to IronPDF. For instance, you could filter only active employees and format their names in uppercase for the PDF output.

var activeEmployees = employees.Where(e => e.IsActive).Select(e => new {
    Name = e.Name.ToUpper(),
    Position = e.Position,
    Age = e.Age
});
var activeEmployees = employees.Where(e => e.IsActive).Select(e => new {
    Name = e.Name.ToUpper(),
    Position = e.Position,
    Age = e.Age
});
Dim activeEmployees = employees.Where(Function(e) e.IsActive).Select(Function(e) New With {
	Key .Name = e.Name.ToUpper(),
	Key .Position = e.Position,
	Key .Age = e.Age
})
VB   C#

This transformed data can then be converted into a PDF-friendly HTML format for rendering.

Batch Generating PDFs from Enumerables

Example: Creating Multiple PDFs from a Collection

If you need to generate a separate PDF for each record in a collection class, you can use a foreach loop to iterate through the enumerable and generate individual PDFs dynamically. This is particularly useful for creating invoices, certificates, or personalized reports.

foreach (var employee in employees)
{
    string html = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>";
    var pdf = Renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs($"{employee.Name}_Report.pdf");
}
foreach (var employee in employees)
{
    string html = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>";
    var pdf = Renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs($"{employee.Name}_Report.pdf");
}
For Each employee In employees
	Dim html As String = $"<h1>{employee.Name}</h1><p>Position: {employee.Position}</p><p>Age: {employee.Age}</p>"
	Dim pdf = Renderer.RenderHtmlAsPdf(html)
	pdf.SaveAs($"{employee.Name}_Report.pdf")
Next employee
VB   C#

Extension Methods for Enumerables

In C#, extension methods are a powerful way to add functionality to existing types without modifying their source code. You can create an extension method to streamline operations on an IEnumerable or List.

For example, let's create an extension method to get the first element from an enumerable collection.

public static class EnumerableExtensions
{
    public static T FirstOrDefaultElement<T>(this IEnumerable<T> collection)
    {
        return collection?.FirstOrDefault();
    }
}
public static class EnumerableExtensions
{
    public static T FirstOrDefaultElement<T>(this IEnumerable<T> collection)
    {
        return collection?.FirstOrDefault();
    }
}
Public Module EnumerableExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Function FirstOrDefaultElement(Of T)(ByVal collection As IEnumerable(Of T)) As T
		Return collection?.FirstOrDefault()
	End Function
End Module
VB   C#

Step-by-Step Implementation

Setting Up the Project

Code Snippet: Initializing IronPDF in C#

Start by setting up your project and initializing IronPDF and the ChromePdfRenderer class:

using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
Imports IronPdf
Private renderer As New ChromePdfRenderer()
VB   C#

Converting Enumerables to PDF Content

Code Snippet: Iterating and Formatting Data into HTML

Prepare your enumerable data as an HTML string:

var employees = new List<Employee>
{
    new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
    new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 }
};
string html = "<table style='width:100%; border: 1px solid black;'>" +
              "<tr><th>Name</th><th>Position</th><th>Age</th></tr>";
foreach (var employee in employees)
{
    html += $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>";
}
html += "</table>";
var employees = new List<Employee>
{
    new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
    new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 }
};
string html = "<table style='width:100%; border: 1px solid black;'>" +
              "<tr><th>Name</th><th>Position</th><th>Age</th></tr>";
foreach (var employee in employees)
{
    html += $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>";
}
html += "</table>";
Dim employees = New List(Of Employee) From {
	New Employee With {
		.Name = "John Doe",
		.Position = "Developer",
		.Age = 30
	},
	New Employee With {
		.Name = "Jane Smith",
		.Position = "Designer",
		.Age = 25
	}
}
Dim html As String = "<table style='width:100%; border: 1px solid black;'>" & "<tr><th>Name</th><th>Position</th><th>Age</th></tr>"
For Each employee In employees
	html &= $"<tr><td>{employee.Name}</td><td>{employee.Position}</td><td>{employee.Age}</td></tr>"
Next employee
html &= "</table>"
VB   C#

Code Snippet: Rendering the HTML to PDF

Convert the HTML to a PDF:

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
Dim pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Employees.pdf")
VB   C#

Full Code Example

Now that we have taken a closer look at how you can use the C# Enumerable class with IronPDF to generate PDF files, let's now take a look at a complete example code wherein we have used these tools to generate a new, dynamic PDF document.

using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
public class Employee
{
    public string Name { get; set; }
    public string Position { get; set; }
    public int Age { get; set; }
}
public class Program
{
    public static void Main(string[] args)
    {
        // Sample employee data
        var employees = new List<Employee>
            {
                new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
                new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 },
                new Employee { Name = "Sam Wilson", Position = "Manager", Age = 35 }
            };
        // Filter and sort data using LINQ
        var filteredEmployees = employees
            .Where(e => e.Age >= 25)
            .OrderBy(e => e.Name)
            .ToList();
        // Generate HTML for the PDF
        string html = "<h1 style='text-align:center;'>Employee Report</h1>" +
                      "<table style='width:100%; border-collapse: collapse;'>" +
                      "<tr style='background-color: #f2f2f2;'>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Name</th>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Position</th>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>";
        foreach (var employee in filteredEmployees)
        {
            html += $"<tr>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" +
                    $"</tr>";
        }
        html += "</table>";
        // Initialize ChromePdfRenderer
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        // Render the HTML to PDF
        try
        {
            var pdf = renderer.RenderHtmlAsPdf(html);
            string outputPath = "EmployeeReport.pdf";
            pdf.SaveAs(outputPath);
            Console.WriteLine($"PDF generated successfully at: {outputPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error generating PDF: {ex.Message}");
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
public class Employee
{
    public string Name { get; set; }
    public string Position { get; set; }
    public int Age { get; set; }
}
public class Program
{
    public static void Main(string[] args)
    {
        // Sample employee data
        var employees = new List<Employee>
            {
                new Employee { Name = "John Doe", Position = "Developer", Age = 30 },
                new Employee { Name = "Jane Smith", Position = "Designer", Age = 25 },
                new Employee { Name = "Sam Wilson", Position = "Manager", Age = 35 }
            };
        // Filter and sort data using LINQ
        var filteredEmployees = employees
            .Where(e => e.Age >= 25)
            .OrderBy(e => e.Name)
            .ToList();
        // Generate HTML for the PDF
        string html = "<h1 style='text-align:center;'>Employee Report</h1>" +
                      "<table style='width:100%; border-collapse: collapse;'>" +
                      "<tr style='background-color: #f2f2f2;'>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Name</th>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Position</th>" +
                      "<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>";
        foreach (var employee in filteredEmployees)
        {
            html += $"<tr>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" +
                    $"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" +
                    $"</tr>";
        }
        html += "</table>";
        // Initialize ChromePdfRenderer
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        // Render the HTML to PDF
        try
        {
            var pdf = renderer.RenderHtmlAsPdf(html);
            string outputPath = "EmployeeReport.pdf";
            pdf.SaveAs(outputPath);
            Console.WriteLine($"PDF generated successfully at: {outputPath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error generating PDF: {ex.Message}");
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf
Public Class Employee
	Public Property Name() As String
	Public Property Position() As String
	Public Property Age() As Integer
End Class
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Sample employee data
		Dim employees = New List(Of Employee) From {
			New Employee With {
				.Name = "John Doe",
				.Position = "Developer",
				.Age = 30
			},
			New Employee With {
				.Name = "Jane Smith",
				.Position = "Designer",
				.Age = 25
			},
			New Employee With {
				.Name = "Sam Wilson",
				.Position = "Manager",
				.Age = 35
			}
		}
		' Filter and sort data using LINQ
		Dim filteredEmployees = employees.Where(Function(e) e.Age >= 25).OrderBy(Function(e) e.Name).ToList()
		' Generate HTML for the PDF
		Dim html As String = "<h1 style='text-align:center;'>Employee Report</h1>" & "<table style='width:100%; border-collapse: collapse;'>" & "<tr style='background-color: #f2f2f2;'>" & "<th style='border: 1px solid black; padding: 8px;'>Name</th>" & "<th style='border: 1px solid black; padding: 8px;'>Position</th>" & "<th style='border: 1px solid black; padding: 8px;'>Age</th></tr>"
		For Each employee In filteredEmployees
			html &= $"<tr>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Name}</td>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Position}</td>" & $"<td style='border: 1px solid black; padding: 8px;'>{employee.Age}</td>" & $"</tr>"
		Next employee
		html &= "</table>"
		' Initialize ChromePdfRenderer
		Dim renderer As New ChromePdfRenderer()
		' Render the HTML to PDF
		Try
			Dim pdf = renderer.RenderHtmlAsPdf(html)
			Dim outputPath As String = "EmployeeReport.pdf"
			pdf.SaveAs(outputPath)
			Console.WriteLine($"PDF generated successfully at: {outputPath}")
		Catch ex As Exception
			Console.WriteLine($"Error generating PDF: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

Output PDF

C# Enumerable (How it Works for Developers): Figure 5

Code Explanation

This C# program is designed to generate a PDF report of filtered employee data using the IronPDF library. The above code begins by defining an Employee class with properties for Name, Position, and Age, representing individual employee records.

A list of sample employee data is created, consisting of three Employee objects with different names, positions, and ages. The program then uses LINQ to filter this list, selecting only employees aged 25 or older, and sorts them alphabetically by name. This filtered and sorted list is stored in the filteredEmployees variable.

Next, the program constructs an HTML string that will be used to generate the PDF. It begins with a heading and a table structure, defining column headers for Name, Position, and Age. It then loops through the filtered employee list, dynamically generating table rows for each employee’s information. The resulting HTML is used to create a PDF via IronPDF’s ChromePdfRenderer.

The above example effectively demonstrates how to use IronPDF to generate a PDF from dynamically generated HTML, showcasing LINQ's power to filter and sort data, and handling exceptions gracefully during the PDF generation process.

Performance Tips and Best Practices

Optimizing Enumerable Operations

Use LINQ to optimize filtering and transformations on your data. For example:

var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
Dim filteredEmployees = employees.Where(Function(e) e.Age > 25).OrderBy(Function(e) e.Name)
VB   C#

Minimize redundant operations by chaining LINQ methods effectively. This improves performance, especially when working with large datasets.

Efficient Memory Usage with Large Data Sets

For large data sets, consider streaming data into smaller chunks to avoid memory overhead. Utilize yield return to generate non generic collection data lazily, ensuring efficient memory usage.

IEnumerable<Employee> GetEmployees() {
    foreach (var employee in database.GetAllEmployees()) {
        yield return employee;
    }
}
IEnumerable<Employee> GetEmployees() {
    foreach (var employee in database.GetAllEmployees()) {
        yield return employee;
    }
}
Private Iterator Function GetEmployees() As IEnumerable(Of Employee)
	For Each employee In database.GetAllEmployees()
		Yield employee
	Next employee
End Function
VB   C#

Error Handling in PDF Generation

Wrap your PDF generation logic in a try-catch block to handle errors gracefully:

try
{
    var pdf = Renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
catch (IronPdf.Exceptions.PdfException ex)
{
    Console.WriteLine($"PDF Error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"General Error: {ex.Message}");
}
try
{
    var pdf = Renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
catch (IronPdf.Exceptions.PdfException ex)
{
    Console.WriteLine($"PDF Error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"General Error: {ex.Message}");
}
Try
	Dim pdf = Renderer.RenderHtmlAsPdf(html)
	pdf.SaveAs("output.pdf")
Catch ex As IronPdf.Exceptions.PdfException
	Console.WriteLine($"PDF Error: {ex.Message}")
Catch ex As Exception
	Console.WriteLine($"General Error: {ex.Message}")
End Try
VB   C#

Logging errors and providing user-friendly feedback can significantly improve the robustness of your application.

Conclusion

The integration of C#'s IEnumerable with IronPDF unlocks an efficient and flexible way to generate professional PDFs programmatically. By leveraging IEnumerable, you can streamline the transformation and formatting of data while taking advantage of IronPDF's rich feature set to produce high-quality documents. Whether you are exporting data reports, creating invoices, or generating personalized content, this combination ensures scalability, performance, and ease of use.

We encourage developers to explore more advanced features of IronPDF, such as embedding multimedia or securing PDFs, to elevate their document automation workflows further. For additional insights, tutorials, and support, refer to the IronPDF Documentation.

< PREVIOUS
C# Parallel Foreach (How it Works for Developers)
NEXT >
C# Events (How it Works for Developers)