跳過到頁腳內容
.NET幫助

C# 可枚舉 (如何為開發人員運作)

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

由於清單實作了 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
});
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
})
$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");
}
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
$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();
    }
}
Imports System.Collections.Generic
Imports System.Linq

Public Module EnumerableExtensions
    <System.Runtime.CompilerServices.Extension>
    Public Function FirstOrDefaultElement(Of T)(collection As IEnumerable(Of T)) As T
        Return If(collection?.FirstOrDefault(), Nothing)
    End Function
End Module
$vbLabelText   $csharpLabel

逐步實施

設定專案

Code Snippet: Initializing IronPDF in C#

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

using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
using IronPdf;
ChromePdfRenderer renderer = new ChromePdfRenderer();
Imports IronPdf
Private renderer As 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>";
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>"
$vbLabelText   $csharpLabel

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

將 HTML 轉換成 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")
$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}");
        }
    }
}
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 a 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
$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);
Dim filteredEmployees = employees.Where(Function(e) e.Age > 25).OrderBy(Function(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;
    }
}
Private Iterator Function GetEmployees() As IEnumerable(Of Employee)
	For Each employee In database.GetAllEmployees()
		Yield employee
	Next employee
End Function
$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}");
}
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
$vbLabelText   $csharpLabel

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

結論

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

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

常見問題解答

IEnumerable如何促進C#中的動態數據操作?

C#中的IEnumerable允許開發人員靈活地遍歷集合以進行動態數據操作。與IronPDF結合使用時,它提供了一種有效的方法來操作數據以生成報告或將數據導出為PDF文檔。

使用IEnumerable的延遲數據處理有什麼好處?

使用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包管理器控制台以命令Install-Package IronPDF在C#項目中安裝,或者通過在解決方案的NuGet包管理器中搜索IronPDF並點擊'Install'進行安裝。

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

IronPDF中的ChromePdfRenderer類對將HTML內容呈現為PDF格式至關重要,提供了一個核心功能來編程生成C#應用程序中的PDF。

如何在生成PDF之前使用LINQ優化數據?

LINQ可以與IEnumerable一起使用,以高效地過濾、排序並將數據投射為所需格式,然後將其傳遞給IronPDF進行PDF生成,從而實現流線型的文檔創建。

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

使用IronPDF生成PDF時的錯誤可以使用try-catch塊來管理,這有助於優雅地處理錯誤和日誌記錄,從而提高應用程序的穩定性。

在使用IEnumerable進行高效數據處理時應遵循哪些最佳實踐?

最佳實踐包括使用LINQ優化數據轉換、最小化冗餘操作,以及利用'yield return'進行延遲數據生成以有效管理內存並提高性能。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我