跳至頁尾內容
.NET幫助

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

排序是任何程式語言中的一個基本操作,C# 的 OrderBy 方法是一個強大的工具,可以排列集合中的元素。 無論是處理陣列、列表或其他列舉結構,了解如何利用 OrderBy 可以大大增強您的程式碼的可讀性和功能性。

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

什麼是 LINQ 的 OrderBy 方法?

OrderBy 方法是 C# 中 LINQ(語言整合查詢)程式庫的一部分,專門設計用來按升序排序元素; 由於這是排序資料的預設方式,因此不需要升序關鍵字。

如何使用 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

在此範例中,將一個自定義的 Person 物件列表根據 Age 屬性按升序排序。

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

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

發現來自Iron Software 的 C# PDF 程式庫中的 IronPDF 功能,它有助於閱讀和生成 PDF 文件。 它可以輕鬆地將帶有樣式資訊的格式化文件轉換為 PDF。 IronPDF 可以從 HTML 字串生成 PDF,或從 URL 下載 HTML 然後生成 PDF。

IronPDF 在將 HTML 轉換為 PDF 方面表現優異,可以保持所有佈局和樣式。 它可以從各種網頁內容(如報告、發票和文件)生成 PDF。 該工具可以使用 HTML 文件、網址和 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 可以顯著提高您的程式碼的清晰度和效率。

與用於生成 PDF 文件的 IronPDF 程式庫 一起,它是一個很好的組合,可以作為文件生成一個精美格式化和排序的集合。

常見問題

C#的OrderBy方法如何運作?

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

如何使用C#按降序排序資料?

要在C#中按降序排序資料,您可以使用OrderByDescending方法。這是LINQ程式庫的一部分,補充了OrderBy以滿足不同的排序需求。

在C#中可以按照多個欄位排序嗎?

是的,在C#中,您可以使用OrderBy與ThenBy或ThenByDescending結合起來按多個欄位排序。這允許根據多重屬性進行複雜的排序準則,讓開發者能夠對集合進行多屬性的排序。

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

自訂比較器在C#中是IComparer介面的實現,提供在排序期間比較元素的自訂邏輯。這對於排序複雜的物件或當預設排序行為不符合特定需求時非常有用。

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

您可以在C#中使用IronPDF從HTML字串、檔案,甚至是網頁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文件。它保留了網頁的原始佈局和樣式,這使其適合存檔網頁或建立可列印版本。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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