在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
排序是任何程式語言中的基本操作,而 C# 的 OrderBy 方法是排列集合內元素的強大工具。 無論是處理陣列、清單,還是其他可列舉的結構,理解如何利用 OrderBy 可以極大地提高代碼的可讀性和功能性。
在本文稍後,我們將介紹Iron Software的IronPDF庫,以及如何使用LINQ的OrderBy方法和IronPDF來生成格式化和排序的PDF。
OrderBy
方法是 C# 中 LINQ(語言集成查詢)庫的一部分,專門用於以升序排列元素。 由於這是排序資料的預設方式,因此不需要使用升序關鍵字。
在 C# 中,有兩種方式可以應用此方法:透過方法語法或查詢語法。 我們將使用方法語法因為它很簡單:
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
Dim sortedCollection = collection.OrderBy(Function(item) item.OrderByProperty)
在此,集合是您想要排序的 IEnumerable
源集合,而 OrderByProperty
是您想要用來排序元素的屬性或表達式。 OrderBy
中的 lambda 表達式擴展方法指定了排序標準。
若要按降序排序,您可以使用方法語法中的OrderByDescending
方法:
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
Dim sortedCollectionDesc = collection.OrderByDescending(Function(item) item.OrderByProperty)
在現實場景中,您通常需要根據多個標準對集合進行排序。 OrderBy
透過鏈接多個 ThenBy
或 ThenByDescending
調用來實現這一點:
var multiSortedCollection = collection
.OrderBy(item => item.OrderByProperty1)
.ThenByDescending(item => item.OrderByProperty2);
var multiSortedCollection = collection
.OrderBy(item => item.OrderByProperty1)
.ThenByDescending(item => item.OrderByProperty2);
Dim multiSortedCollection = collection.OrderBy(Function(item) item.OrderByProperty1).ThenByDescending(Function(item) item.OrderByProperty2)
在此範例中,集合首先按照 OrderByProperty1 以升序排序。 接著,對於具有相同 OrderByProperty1 值的元素,將按 OrderByProperty2 以降序排序。
對於更複雜的排序要求,您可以使用自定義比較器。 OrderBy
方法允許您傳遞一個 IComparer<T>
實現,如下範例所示:
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
Dim customSortedCollection = collection.OrderBy(Function(item) item.Property, New CustomComparer())
這裡,CustomComparer
是實現 IComparer<T>
介面的類別,提供比較元素的自定義邏輯。
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("Sorted Numbers:");
foreach (var number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("Sorted Numbers:");
foreach (var number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim numbers As New List(Of Integer) From {5, 2, 8, 1, 7}
Dim sortedNumbers = numbers.OrderBy(Function(num) num)
Console.WriteLine("Sorted Numbers:")
For Each number In sortedNumbers
Console.WriteLine(number)
Next number
End Sub
End Class
在此範例中,使用OrderBy
對一個整數列表進行升序排序。
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
var sortedNames = names.OrderBy(name => name);
Console.WriteLine("Sorted Names:");
foreach (var name in sortedNames)
{
Console.WriteLine(name);
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
var sortedNames = names.OrderBy(name => name);
Console.WriteLine("Sorted Names:");
foreach (var name in sortedNames)
{
Console.WriteLine(name);
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim names As New List(Of String) From {"Alice", "Charlie", "Bob", "David"}
Dim sortedNames = names.OrderBy(Function(name) name)
Console.WriteLine("Sorted Names:")
For Each name In sortedNames
Console.WriteLine(name)
Next name
End Sub
End Class
此範例演示了按字母順序對字串列表進行遞增排序。
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
Console.WriteLine("Sorted People by Age:");
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
Console.WriteLine("Sorted People by Age:");
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Person
Public Property FirstName() As String
Public Property LastName() As String
Public Property Age() As Integer
End Class
Friend Class Program
Shared Sub Main()
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe",
.Age = 30
},
New Person With {
.FirstName = "Alice",
.LastName = "Smith",
.Age = 25
},
New Person With {
.FirstName = "Bob",
.LastName = "Johnson",
.Age = 35
}
}
Dim sortedPeople = people.OrderBy(Function(person) person.Age)
Console.WriteLine("Sorted People by Age:")
For Each person In sortedPeople
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}")
Next person
End Sub
End Class
在此範例中,自訂 Person 物件的清單依據年齡屬性進行遞增排序。
以下輸出在控制台中可見
當處理字串屬性時,您可能希望確保不區分大小寫的排序:
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
Dim sortedPeopleByName = people.OrderBy(Function(person) person.LastName, StringComparer.OrdinalIgnoreCase)
此範例使用StringComparer.OrdinalIgnoreCase
來基於LastName
屬性進行不區分大小寫的排序。
雖然 LINQ 提供了一種簡潔的方法來排序集合,但對於大型數據集來說,考慮效能影響是至關重要的。 對於性能關鍵的場景,您可以考慮使用List<T>.Sort
方法進行就地排序等替代方案。
探索IronPDF的功能,這是Iron Software提供的C# PDF庫,幫助閱讀和生成PDF文檔。 它可以輕鬆將帶有樣式資訊的格式化文件轉換為 PDF。 IronPDF 可以從 HTML 字串生成 PDF,或者可以從 URL 下載 HTML 然後生成 PDF。
IronPDF 在將 HTML 轉換為 PDF時表現出色,並保留所有佈局和樣式。 它可以從各種網頁內容生成 PDF,例如報告、發票和文檔。 該工具使用 HTML 文件、URL 和 HTML 字串來創建 PDF 文件。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
IronPDF 可以使用 NuGet 套件管理控制台 或使用 Visual Studio 套件管理器來安裝。
dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
您還可以使用 NuGet 套件管理器安裝 IronPDF,只需在搜尋欄中搜尋 "ironpdf"。
以下是使用 HTML 字串和 IronPDF 生成器生成 PDF 報告的程式碼:
// See https://aka.ms/new-console-template for more information
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
string name = "Sam";
var count = people.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" +
string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
}
}
// See https://aka.ms/new-console-template for more information
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
string name = "Sam";
var count = people.Count;
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" +
string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
}
}
Imports Microsoft.VisualBasic
' See https://aka.ms/new-console-template for more information
Friend Class Person
Public Property FirstName() As String
Public Property LastName() As String
Public Property Age() As Integer
End Class
Friend Class Program
Shared Sub Main()
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe",
.Age = 30
},
New Person With {
.FirstName = "Alice",
.LastName = "Smith",
.Age = 25
},
New Person With {
.FirstName = "Bob",
.LastName = "Johnson",
.Age = 35
}
}
Dim sortedPeople = people.OrderBy(Function(person) person.Age)
Dim name As String = "Sam"
Dim count = people.Count
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" & String.Join(vbLf, sortedPeople.Select(Function(person) $"{person.FirstName} {person.LastName}, Age: {person.Age}")) & "
</body>
</html>"
' Create a new PDF document
Dim pdfDocument = New ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf")
End Sub
End Class
首先,我們從sortedPeople
生成一個 HTML 字串,該字串以升序排序,並包含報告所需的所有格式。 然後我們使用IronPDF生成PDF文件。 我們使用RenderHtmlAsPdf
方法將HTML字串轉換為PDF文件。
以下輸出可在 PDF 中獲得。
試用金鑰可以從IronPDF 試用授權獲得。 此鍵需要放置在 appsettings.json 中。
"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
提供您的電子郵件以獲取試用許可證。
C# 中的 OrderBy 方法是一個多功能工具,可根據各種標準對集合進行排序。 無論您是按照升序還是降序排序,按單一或多個準則排序,或使用自定義比較器,掌握 OrderBy 可以顯著提高您的代碼的清晰度和效率。
與IronPDF 程式庫用於生成 PDF 文件相結合,這是一個完美的組合,可作為文檔生成格式精美且排序整齊的集合。