C# 可枚舉 (如何為開發人員運作)
C# 的 IEnumerable 介面是 .NET Framework 中最通用的工具之一,使開發人員能夠以高度靈活的方式處理集合。 當與 IronPDF 結合時,IEnumerable 允許動態資料操作和高效的 PDF 生成,使其非常適合建立報告、導出資料或從資料庫查詢生成文件的場景。 using IEnumerable 可確保您的應用程式保持可擴展性和記憶體效率,因為它延遲處理資料,並且避免一次將整個資料集載入到記憶體中。 這對於處理大量資料集合的大規模應用尤其有用,例如大型資料庫表。
什麼是IronPDF?

IronPDF 是一個強大的 .NET 程式庫,旨在簡化以程式方式建立、編輯和管理 PDF 文件的過程。 它提供了廣泛的功能,包括 HTML 到 PDF 的轉換、文字提取、PDF 合併等。 通過將 IronPDF 整合到您的 C# 專案中,您可以高效地處理複雜的 PDF 任務,而無需深入了解 PDF 的內部原理。
IronPDF 亦支援多種格式,使您能夠從原始 HTML、Razor Views、ASP.NET 網頁甚至直接從資料結構生成 PDF。 這種靈活性使其成為構建現代資料驅動應用的開發人員的重要工具。
開始使用
安裝IronPDF
若要在您的專案中使用 IronPDF,請按照以下步驟操作:
透過 NuGet 套件管理器控制台
- 在 Visual Studio 中打開您的 .NET 專案。
- 在工具下拉選單中打開 NuGet 套件管理器控制台。

- 執行以下命令:
Install-Package IronPdf
透過解決方案的 NuGet 套件管理器
- 在 Visual Studio 專案中,前往工具 > NuGet 套件管理器 > 管理解決方案的 NuGet 套件。
- 搜尋 IronPDF。

- 按"安裝"開始將 IronPDF 套件安裝到您的專案中。

Basic Concepts of Enumerable in C
IEnumerable 介面表示可列舉的元素序列。 常見的例子包括陣列、列表和 LINQ 查詢結果。 通過利用 LINQ,您可以在使用 IronPDF 生成 PDF 之前過濾、排序和投影資料為所需的格式。
IEnumerable 的一個主要優勢是其延遲執行模型,允許僅在存取結果時執行查詢。 這使得資料操作高效,並減少複雜工作流程中的計算開銷。
由於列表實現了 IEnumerable,因此任何集合,例如 List,都可以視為 IEnumerable,從而輕鬆執行 LINQ 操作、過濾和轉換。
實際使用案例
從 Enumerable 資料生成 PDF
範例:將物件列表匯出為 PDF 表格
假設您有一個實現了員工 IEnumerable 的列表,需要將其匯出為 PDF 表格。 使用 IEnumerable 和 IronPDF,您可以遍歷資料並將其轉換為具有良好結構的 PDF。
為了增強演示,您可以使用具有內嵌 CSS 的 HTML 表格來根據資料動態設置行和列的樣式。 這可確保 PDF 輸出既具功能性,又具視覺吸引力。
在 PDF 生成前過濾和轉換資料
範例:使用 LINQ 選擇和格式化資料
using 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
})
然後,這些轉換後的資料可以轉換為 PDF 友好的 HTML 格式進行渲染。
從 Enumerables 批量生成 PDF
範例:從集合建立多個 PDF
如果您需要為集合中的每條記錄生成單獨的 PDF,您可以使用 foreach 迴圈迭代遍歷 enumerable,並動態生成各個 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
Enumerables 的擴充方法
在 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
分步實施
設置專案
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()
將 Enumerables 轉換為 PDF 內容
程式碼片段:迭代並將資料格式化為 HTML
將您的 enumerable 資料準備為字串格式的 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>"
程式碼片段:渲染 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")
完整程式碼範例
現在我們已經仔細研究了如何使用 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
輸出 PDF

程式碼説明
這個 C# 程式的設計目的是使用 IronPDF 程式庫生成過濾後的員工資料的 PDF 報告。 上面的程式碼首先定義了一個擁有 Name、Position 和 Age 屬性的 Employee 類,這代表了個別的員工記錄。
建立了一個樣本員工資料列表,包含三個具有不同姓名、職位和年齡的 Employee 物件。 然後,該程式使用 LINQ 過濾此列表,僅選擇年齡在 25 歲或以上的員工,並按姓名字母順序排序。 此已過濾和排序的列表儲存在 filteredEmployees 變數中。
接下來,程式構建了一個用於生成 PDF 的 HTML 字串。 它從標題和表格結構開始,定義了 Name、Position 和 Age 的列標題。 然後,遍歷已過濾的員工列表,動態生成每位員工資訊的表格行。 生成的 HTML 用 IronPDF 的 ChromePdfRenderer 生成 PDF。
上述範例有效展示了如何使用 IronPDF 從動態生成的 HTML 生成 PDF,展示了 LINQ 過濾和排序資料的強大功能,並在 PDF 生成過程中優雅地處理例外情況。
性能提示和最佳實踐
優化 Enumerable 操作
using 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)
通過有效地連結 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
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
記錄錯誤和提供友好的使用者反饋可以顯著提高您應用程式的魯棒性。
結論
C# 的 IEnumerable 與 IronPDF 的整合解鎖了一種高效且靈活的方式來程式化生成專業 PDF。 通過利用 IEnumerable,您可以簡化資料的轉換和格式化,同時利用 IronPDF 的豐富功能集來生成高品質的文件。 無論您是匯出資料報告、建立發票,還是生成個性化內容,這樣的組合可確保擴展性、性能和易用性。
我們鼓勵開發人員探索 IronPDF 的更高階功能,例如嵌入多媒體或保護 PDF,以進一步提升他們的文件自動化工作流程。 有關更多見解、教程和支援,請參考 IronPDF 說明文件.
常見問題
IEnumerable 如何在 C# 中促進動態資料操作?
C# 中的 IEnumerable 允許動態資料操作,讓開發者能夠靈活地迭代集合。當與 IronPDF 結合使用時,它提供了一種有效的方法來操作資料以生成報告或將資料匯出到 PDF 文件中。
using IEnumerable 進行延遲資料處理有何好處?
using IEnumerable 進行延遲資料處理通過僅在需要時處理資料提升了可擴展性和記憶體效率。這在處理大型資料集時特別有益,因為它避免了一次性將整個資料集載入記憶體。
如何使用 .NET 程式庫在 C# 中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。此外,也可以使用 RenderHtmlFileAsPdf 方法將 HTML 文件轉換為 PDF。
IEnumerable 在文件生成方面有何實際應用?
IEnumerable 可以用來將物件列表匯出到 PDF 表格中、在 PDF 生成前執行資料過濾和轉換、並利用 IronPDF 的特性從集合中批量生成 PDF。
如何在 C# 專案中安裝 IronPDF 以進行 PDF 生成?
IronPDF 可以通過在 Visual Studio 中的 NuGet 套件管理器控制台使用命令 Install-Package IronPdf 安裝,或者通過 NuGet 套件管理器搜尋 IronPDF 並點擊 '安裝'。
ChromePdfRenderer 類在 PDF 生成中有什麼作用?
IronPDF 中的 ChromePdfRenderer 類對於將 HTML 內容渲染為 PDF 格式至關重要,提供了程式化生成 PDF 的核心功能。
如何使用 LINQ 在生成 PDF 之前優化資料?
LINQ 可以與 IEnumerable 結合使用,以便在將資料傳遞給 IronPDF 生成 PDF 之前,對資料進行有效的過濾、排序和映射,從而實現流暢的文件建立。
如何在 C# 應用程式中處理 PDF 生成過程中的錯誤?
using IronPDF 生成 PDF 時,可以通過 try-catch 區塊來管理錯誤,這有助於優雅地處理和日誌記錄錯誤,從而提高應用程式的穩健性。
using IEnumerable 的最佳做法是什麼,以便有效地處理資料?
最佳做法包括使用 LINQ 優化資料轉換、最大限度地減少冗餘操作,並利用 'yield return' 進行延遲資料生成來有效管理記憶體並提升性能。




