.NET 幫助

C# Enumerable(對開發者而言的運作方式)

Chipego
奇佩戈·卡林达
2025年1月14日
分享:

介紹

C# 的 IEnumerable介面是 .NET 框架中最具多功能性的工具之一,讓開發人員能夠以高度彈性的方式處理集合。 結合時IronPDFIEnumerable 允許動態數據操作和高效 PDF 生成,這使其非常適合於創建報告、導出數據或從數據庫查詢生成文檔等情境。

使用 IEnumerable 確保您的應用程式保持可擴展性和記憶體效能,因為它以惰性方式處理資料,並避免一次將整個資料集加載到記憶體中。 這對於處理大量數據集的大型應用程式尤其有用,例如一個巨大的資料庫表。

什麼是 IronPDF?

C# Enumerable(對開發人員的運作方式):圖 1

IronPDF 是一個強大的 .NET 函式庫,旨在簡化以程式方式創建、編輯和管理 PDF 檔案的過程。 它提供了廣泛的功能,包括 HTML 轉換為 PDF、文字提取、PDF 合併等。 通過將 IronPDF 集成到您的 C# 項目中,您可以有效處理複雜的 PDF 任務,而不需要深入了解 PDF 的內部結構。

IronPDF 也支持多種格式,允許您從原始 HTML、Razor Views、ASP.NET 網頁,甚至直接從數據結構生成 PDF。 這種靈活性使其成為開發人員構建現代數據驅動應用程式的基本工具。

入門

安裝 IronPDF

要在您的專案中使用IronPDF,請按以下步驟操作:

透過 NuGet 套件管理器主控台

  1. 在 Visual Studio 中打開您的 .NET 專案。

    1. 在工具下拉選單中打開 NuGet 套件管理員主控台。

    C# Enumerable(開發人員運作方式):圖2

  2. 運行以下命令:
Install-Package IronPdf
Install-Package IronPdf

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

  1. 在您的 Visual Studio 專案中,前往 工具 > NuGet 套件管理員 > 管理解決方案的 NuGet 套件

    1. 搜索 IronPDF

    C# Enumerable(開發者如何運作):圖 3

    1. 點擊「Install」開始將 IronPDF 套件安裝到您的專案中。

    C# Enumerable(開發人員如何使用):圖4

C#中 Enumerable 的基本概念

IEnumerable 介面表示可以列舉的元素序列。 常見的例子包括陣列、清單和 LINQ 查詢結果。 透過使用 LINQ,您可以在使用 IronPDF 生成 PDF 之前,將資料篩選、排序及投影至所需的格式。

IEnumerable 的其中一個主要優勢是其延遲執行模型,讓查詢僅在訪問結果時才被執行。 這可實現高效的數據操作並減少複雜工作流程中的計算開銷。

此外,清單實作 IEnumerable,這意味著任何像是 List的集合都可以視為 IEnumerable,從而能夠輕鬆進行 LINQ 操作、篩選和轉換。

實用案例

從可列舉數據生成PDF

範例:將物件列表匯出到 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
});

然後,這個轉換後的數據可以被轉換成適合 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");
}

可列舉的擴充方法

在 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();
    }
}

逐步實現

設置專案

程式碼片段:在 C# 中初始化 IronPDF

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

using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();

將列舉轉換為 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>";

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

將 HTML 轉換為 PDF:

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

完整代碼範例

現在我們已經仔細看看如何使用 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 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}");
        }
    }
}

輸出 PDF

C# Enumerable(開發者如何使用):圖5

程式碼說明

此C#程式旨在使用IronPDF庫生成過濾後的員工數據PDF報告。 上述程式碼首先定義了一個 Employee 類別,包含 Name、Position 和 Age 屬性,代表單個員工記錄。

建立了一個樣本員工數據列表,包括三個具有不同名稱、職位和年齡的員工對象。 接著,程序使用 LINQ 篩選此清單,選擇年齡在 25 歲或以上的員工,並按名字的字母順序排序。 這個過濾和排序後的列表存儲在 filteredEmployees 變數中。

接下來,程序構建一個將用於生成 PDF 的 HTML 字串。 它以標題和表格結構開始,定義了姓名、職位和年齡的欄目標題。 然後,它遍歷篩選後的員工列表,動態生成每個員工信息的表格行。 生成的 HTML 用於通過 IronPDF 創建 PDFChromePdfRenderer.

上述範例有效地展示了如何使用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);

通過有效鏈接 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;
    }
}

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

記錄錯誤並提供用戶友好的反饋可以顯著提高應用程式的穩健性。

結論

C# 的 IEnumerable 與... 的整合IronPDF解鎖一種以程式方式生成專業 PDF 的高效且靈活的方法。 通過利用 IEnumerable,您可以簡化數據的轉換和格式化,並利用 IronPDF 的豐富功能集生產高品質的文檔。 無論您是匯出數據報告、製作發票,還是生成個性化內容,這個組合都能確保其可擴展性、性能和易用性。

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

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 平行 Foreach(其如何運作對於開發者)
下一個 >
C# 事件(開發者如何運作)