跳過到頁腳內容
.NET幫助

C# Orderby(對於開發者的運行原理)

排序是任何程式語言中基本的操作,C# 的 OrderBy 方法是一個用於在集合內排列元素的強大工具。 無論是處理陣列、清單或其他可列舉的結構,瞭解如何使用 OrderBy 都能大幅提升程式碼的可讀性和功能性。

在本文的後面,我們將介紹 Iron Software 的 IronPDF 庫,以及如何利用 LINQ 的 OrderBy 方法和 IronPDF 來生成格式化和排序的 PDF。

什麼是 LINQ 的 OrderBy 方法?

OrderBy 方法是 C# 的 LINQ(Language-Integrated Query)庫的一部分,專門用於以升序排列元素; 由於排序資料的預設方式為升序,因此不需要特別指定升序關鍵字。

如何使用 LINQ 的 OrderBy 方法

以升序排列資料

在 C# 中,有兩種方式可以應用此方法:通過方法語法或查詢語法。 我們將使用方法語法,因為它比較簡單明瞭:

var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
Dim sortedCollection = collection.OrderBy(Function(item) item.OrderByProperty)
$vbLabelText   $csharpLabel

此處的 collection 指的是您要排序的 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)
$vbLabelText   $csharpLabel

依多重條件排序資料

在實際情況中,您時常需要根據多重條件排序一個集合。 OrderBy 允許通過連接多個 ThenByThenByDescending 呼叫來實現這一點:

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

在此示例中,集合首先根據 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())
$vbLabelText   $csharpLabel

此處的 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
$vbLabelText   $csharpLabel

在此示例中,整數列表使用 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
$vbLabelText   $csharpLabel

此示例展示了按字母順序以升序排序字串列表。

排序自訂物件列表

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

在此示例中,依據 Age 屬性升序排列自訂的 Person 物件列表。

以下輸出可在控制台中看到:

C# Orderby(對開發者的作用):圖 1 - 上述代碼對自訂物件排序的輸出

處理字串比較

在處理字串屬性時,您可能希望確保不區分大小寫的排序:

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

此示例使用 StringComparer.OrdinalIgnoreCase 來對 LastName 屬性進行不區分大小寫的排序。

性能考量

雖然 LINQ 提供了一種簡潔的方式來排序集合,但在處理大型資料集時,考慮性能影響是很重要的。 對於性能要求較高的情況,您可能會考慮其他替代方案,如使用 List<T>.Sort 方法進行就地排序。

介绍 IronPDF

Discover IronPDF capabilities within the C# PDF library from Iron Software,協助閱讀和生成 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
$vbLabelText   $csharpLabel

安裝

IronPDF 可以通過 NuGet 套件管理器控制台 或使用 Visual Studio 套件管理器安裝。

Install-Package IronPdf

您也可以通過在搜尋欄中搜索「ironpdf」,使用 NuGet Package Manager 安裝 IronPDF。

C# Orderby(對開發者的作用):圖 2 - 通過 NuGet Package Manager 安裝 IronPDF

使用 IronPDF 生成 PDF

以下是使用 HTML 字串和 IronPDF 生成 PDF 報告的程式碼:

// See https://aka.ms/new-console-template for more information

using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

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

        // Sort people by age
        var sortedPeople = people.OrderBy(person => person.Age);

        string name = "Sam";
        var count = people.Count;

        // Generate an HTML string
        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 and save it
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
    }
}
// See https://aka.ms/new-console-template for more information

using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

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

        // Sort people by age
        var sortedPeople = people.OrderBy(person => person.Age);

        string name = "Sam";
        var count = people.Count;

        // Generate an HTML string
        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 and save it
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
    }
}
' See https://aka.ms/new-console-template for more information

Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq

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
			}
		}

		' Sort people by age
		Dim sortedPeople = people.OrderBy(Function(person) person.Age)

		Dim name As String = "Sam"
		Dim count = people.Count

		' Generate an HTML string
		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 and save it
		Dim pdfDocument = New ChromePdfRenderer()
		pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡我們首先從 sortedPeople 中生成一個升序排列的 HTML 字串,其中包含所有所需報告的格式。 然後我們使用 IronPDF 來生成 PDF 文檔。 我們使用 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF 文檔。

輸出

以下輸出可在 PDF 中看到:

C# Orderby(對開發者的作用):圖 3 - 上述代碼的 PDF 輸出

許可(可用免費試用)

可從 IronPDF 試用許可證 獲取試用金鑰。 此金鑰需要放置在 appsettings.json 中。

"IronPdf.LicenseKey": "your license key"

提供您的電子郵件以獲取試用許可證。

結論

C# 中的 OrderBy 方法是一種多功能的工具,用於依據各種條件排序集合。 無論您是按升序還是降序排序,基於單一條件還是多重條件排序,或使用自訂比較器,掌握 OrderBy 都能大幅提升程式碼的清晰度和效率。

IronPDF 庫用於生成 PDF 文檔結合使用,是生成美觀格式化和排序的文檔的絕佳搭配。

常見問題解答

C# 的 OrderBy 方法如何運作?

C# 的 OrderBy 方法是 LINQ 庫的一部分,用於將集合的元素按升序排序。它既可以用方法語法也可以用查詢語法,並且足夠靈活,可以處理整數、字串和自定義物件。

如何使用 C# 對數據進行降序排序?

要在 C# 中對數據進行降序排序,您可以使用 OrderByDescending 方法。這是 LINQ 庫的一部分,並補充 OrderBy 以滿足不同的排序需求。

是否可以在 C# 中按多個字段排序?

是的,在 C# 中,可以將 OrderBy 與 ThenBy 或 ThenByDescending 結合使用來按多個字段排序。這允許複雜的排序標準,使開發人員能夠根據多個屬性對集合進行排序。

什麼是自定義比較器,如何在 C# 排序中使用它?

C# 中的自定義比較器是一個 IComparer 介面的實現,提供了在排序過程中比較元素的自定義邏輯。這對於排序複雜對象或當默認排序行為不符合特定要求時非常有用。

如何使用 IronPDF 在 C# 中生成 PDF?

您可以在 C# 中使用 IronPDF 從 HTML 字串、文件甚至 Web URL 生成 PDF。IronPDF 保持原始內容的佈局和樣式,非常適合創建報告和發票等專業文檔。

在 C# 項目中安裝 IronPDF 的步驟是什麼?

IronPDF 可以使用 NuGet 套件管理器安裝到 C# 項目中。您可以在控制台中執行命令 dotnet add package IronPdf 或使用 Visual Studio 中的套件管理器將其添加到您的項目中。

IronPDF 如何與 C# OrderBy 整合以生成 PDF?

IronPDF 可以與 C# OrderBy 結合創建排序和格式化的 PDF 報告。通過在渲染之前使用 OrderBy 對數據集合進行排序,確保 PDF 輸出根據您的排序標準進行組織。

IronPDF 是否可以將網頁 URL 轉換成 PDF?

是的,IronPDF 可以將來自 URL 的網頁內容轉換成 PDF 文檔。它保留了網頁的原始佈局和風格,非常適合存檔網頁或創建可打印版本。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。