跳過到頁腳內容
.NET HELP

C# Enumerable (How it Works for Developers)

C# 的 IEnumerable 介面是 .NET Framework 中功能最齊全的工具之一,可讓開發人員以高度靈活的方式處理集合。 當與 IronPDF 結合時,IEnumerable 允許動態資料操作和高效的 PDF 產生,使其成為建立報告、匯出資料或從資料庫查詢產生文件等情境的理想選擇。

使用 IEnumerable 可確保您的應用程式保持可擴充性且節省記憶體,因為它會懶惰地處理資料,並避免一次將整個資料集載入記憶體。 這對於處理大量資料集合的大型應用程式尤其有用,例如大量的資料庫表格。

什麼是 IronPDF?

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

IronPDF for .NET 是一個功能強大的 .NET 函式庫,旨在簡化以程式化方式建立、編輯和管理 PDF 檔案的過程。 它提供廣泛的功能,包括 HTML 至 PDF 轉換、文字萃取、PDF 合併等。 將 IronPDF 整合到您的 C# 專案中,您就可以有效率地處理複雜的 PDF 任務,而不需要深厚的 PDF 內部專業知識。

IronPDF 也支援多種格式,可讓您從原始 HTML、Razor View、ASP.NET 網頁,甚至直接從資料結構產生 PDF。 這種靈活性使其成為開發人員建立現代化、資料驅動應用程式的必備工具。

開始

安裝 IronPDF

若要在您的專案中使用 IronPDF,請遵循下列步驟:

透過 NuGet 套件管理員控制台

1.在 Visual Studio 中開啟您的 .NET 專案。 2.在工具下拉選單中開啟 NuGet Package Manager Console。

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

3.執行下列指令:

Install-Package IronPdf

透過 NuGet 套件管理器的解決方案

1.在您的 Visual Studio 專案中,前往 tools > NuGet Package Manager > Manage NuGet Packages for Solution。 2.搜尋 IronPdf。

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

3.點擊"安裝"開始將 IronPdf 套件安裝到您的專案中。

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

C# 中可枚舉的基本概念;

IEnumerable 介面代表可枚举的元素序列。 常見的例子包括陣列、列表和 LINQ 查詢結果。 利用 LINQ,您可以在使用 IronPDF 生成 PDF 之前將資料篩選、排序並投影成所需格式。

IEnumerable 的主要優勢之一是其遞延執行模型,它允許只在存取結果時才執行查詢。 這樣才能在複雜的工作流程中有效率地操作資料並減少運算開銷。

由於 list 實作了 IEnumerable,因此任何集合(如 List)都可以視為 IEnumerable,從而可以輕鬆進行 LINQ 操作、篩選和轉換。

實用案例

從可枚举資料產生 PDFs

範例:將物件清單匯出至 PDF 表格

想像您有一個實作 IEnumerable 的員工清單,需要匯出成 PDF 表格。 使用 IEnumerable 和 IronPDF,您可以遍历数据并将其转换为结构良好的 PDF。

為了增強呈現效果,您可以使用內嵌 CSS 的 HTML 表格,根據資料動態地設定行與列的樣式。 這可確保 PDF 輸出兼具功能性與視覺吸引力。

在 PDF 生成之前過濾和轉換資料

範例:使用 LINQ 來選擇和格式化資料

使用 LINQ,您可以在將資料傳給 IronPDF 之前先過濾和轉換資料。 例如,您可以僅篩選在職員工,並在 PDF 輸出中將他們的姓名格式化為大寫。

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
});
$vbLabelText   $csharpLabel

然後,這些轉換過的資料可以轉換成 PDF 友善的 HTML 格式,以便渲染。

從枚举式 PDF 批量生成

範例:從一個集合建立多個 PDF

如果您需要為集合中的每條記錄產生單獨的 PDF,您可以使用 foreach 環路遍歷可枚举的記錄,並動態產生單獨的 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");
}
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");
}
$vbLabelText   $csharpLabel

可枚举的扩展方法

在 C# 中,擴充方法是一種強大的方式,可在不修改現有類型的原始程式碼的情況下,為其增加功能。 您可以建立擴充方法,以簡化對 IEnumerable 或 List 的操作。

例如,讓我們建立一個擴充方法,從一個可枚举的集合中取得第一個元素。

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();
    }
}
$vbLabelText   $csharpLabel

逐步實施

設定專案

程式碼片段:在 C&num 中初始化 IronPDF;

首先設定您的專案,並初始化 IronPDF 和 ChromePdfRenderer 類:

using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
$vbLabelText   $csharpLabel

將枚举式內容轉換為 PDF 內容

程式碼片段:將資料迭代並格式化為 HTML

將您的可枚舉資料準備為 HTML 字串:

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>";
$vbLabelText   $csharpLabel

程式碼片段:將 HTML 渲染成 PDF

將 HTML 轉換成 PDF:

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Employees.pdf");
$vbLabelText   $csharpLabel

完整程式碼範例

現在,我們已經仔細了解了如何使用 C# Enumerable 類與 IronPDF 來產生 PDF 檔案,讓我們來看看一個完整的範例程式碼,在這個範例程式碼中,我們使用這些工具來產生一個新的動態 PDF 文件。

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 a 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 a 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}");
        }
    }
}
$vbLabelText   $csharpLabel

輸出 PDF

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

程式碼解釋

此 C# 程式旨在使用 IronPDF 函式庫,將篩選後的員工資料產生 PDF 報告。 上述程式碼首先定義 Employee 類別,該類別具有姓名、職位和年齡的屬性,代表個別的員工記錄。

建立一份員工資料範例清單,其中包含三個具有不同姓名、職位和年齡的 Employee 物件。 然後,程式使用 LINQ 篩選此清單,僅選取年齡在 25 歲以上的員工,並依姓名的字母順序排序。 這個經過篩選和排序的清單儲存於 filteredEmployees 變數中。

接下來,程式會建構一個 HTML 字串,用來產生 PDF。 它以標題和表格結構開始,定義了姓名、職位和年齡的欄頭。 翻譯程式會在經過篩選的員工清單中進行循環,動態地為每位員工的資訊產生表格行。 翻譯後的 HTML 將透過 IronPDF 的 ChromePdfRenderer 產生 PDF。

上述範例有效地示範如何使用 IronPDF 從動態產生的 HTML 產生 PDF,展示 LINQ 篩選和排序資料的能力,以及在 PDF 產生過程中優雅地處理異常。

效能提示與最佳實務

優化可枚舉運算

使用 LINQ 來優化資料的篩選與轉換。 舉例來說

var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
var filteredEmployees = employees.Where(e => e.Age > 25).OrderBy(e => e.Name);
$vbLabelText   $csharpLabel

透過有效鏈結 LINQ 方法,將冗餘的操作減至最少。 這樣可以提高效能,尤其是在處理大型資料集時。

大型資料集的高效記憶體使用

對於大型資料集,請考慮將資料串流為較小的區塊,以避免記憶體開銷。 利用 yield return 懶惰地產生集合,確保記憶體的有效使用。

IEnumerable<Employee> GetEmployees()
{
    foreach (var employee in database.GetAllEmployees())
    {
        yield return employee;
    }
}
IEnumerable<Employee> GetEmployees()
{
    foreach (var employee in database.GetAllEmployees())
    {
        yield return employee;
    }
}
$vbLabelText   $csharpLabel

PDF 生成中的错误处理

將您的 PDF 生成邏輯包裝在 try-catch 區塊中,以便優雅地處理錯誤:

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}");
}
$vbLabelText   $csharpLabel

記錄錯誤和提供使用者友善的回饋,可以大幅提升應用程式的穩健性。

結論

C# 的 IEnumerable 與 IronPDF的整合,開啟了以程式化方式產生專業 PDF 的有效且彈性的方法。 利用 IEnumerable,您可以簡化資料的轉換和格式化,同時利用 IronPDF 的豐富功能集製作高品質文件。 無論是匯出資料報告、建立發票,或是產生個人化內容,這樣的組合都能確保擴充能力、效能和易用性。

我們鼓勵開發人員探索 IronPDF 更先進的功能,例如嵌入多媒體或保護 PDF,以進一步提升他們的文件自動化工作流程。 如需更多深入瞭解、教學和支援,請參閱 IronPDF 文件

常見問題解答

IEnumerable 如何促進 C# 中的動態資料處理?

C# 中的 IEnumerable 使開發人員能夠靈活地迭代集合,從而實現動態資料操作。與 IronPDF 搭配使用時,可提供有效的資料處理方式,以產生報表或將資料匯出成 PDF 文件。

使用 IEnumerable 進行 lazy 資料處理有什麼好處?

使用 IEnumerable 進行懶惰資料處理,可透過只在需要時才處理資料來增強可擴充性和記憶體效率。這對於處理大型資料集特別有利,因為可以避免一次將整個資料集載入記憶體。

如何使用 .NET 函式庫在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。此外,也可以使用 RenderHtmlFileAsPdf 方法將 HTML 檔案轉換為 PDF。

IEnumerable 在文件生成中有哪些實際應用?

IEnumerable 可用於將對象清單匯出成 PDF 表格、在 PDF 生成前執行資料篩選與轉換,以及從集合批量生成 PDF,同時充分利用 IronPDF 的功能。

如何在 C# 專案中安裝 IronPDF 以產生 PDF?

IronPDF 可使用 Visual Studio 中的 NuGet Package Manager Console,透過 Install-Package IronPdf 指令安裝在 C# 專案中,或透過 NuGet Package Manager for Solutions,搜尋 IronPDF 並點選「安裝」。

ChromePdfRenderer 類別在 PDF 生成中扮演什麼角色?

IronPDF 中的 ChromePdfRenderer 類對於將 HTML 內容渲染為 PDF 格式是必不可少的,它提供了在 C# 應用程式中程式化生成 PDF 的核心功能。

在生成 PDF 之前,如何使用 LINQ 來優化資料?

LINQ 可與 IEnumerable 搭配使用,以有效率地將資料篩選、排序並投射成所需格式,再傳送至 IronPDF 以產生 PDF,進而簡化文件的建立。

如何在 C# 應用程式中處理 PDF 生成過程中的錯誤?

使用 IronPdf 生成 PDF 的過程中發生的錯誤可以使用 try-catch 區塊進行管理,這有助於優美的錯誤處理和日誌記錄,從而提高應用程式的穩健性。

使用 IEnumerable 進行有效率的資料處理時,應該遵循哪些最佳實務?

最佳實務包括使用 LINQ 來最佳化資料轉換、盡量減少多餘的作業,以及利用「收益回報」來產生懶惰資料,以有效管理記憶體並提昇效能。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。