.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

在这里,集合是你想要排序的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.OrdinalIgnoreCaseLastName属性进行不区分大小写的排序。

性能考虑事项

虽然LINQ提供了简洁的方法来对集合进行排序,但对于大数据集,考虑性能影响是至关重要的。 对于性能至关重要的场景,您可以探索替代方法,例如使用List<T>.Sort方法进行就地排序。

介绍IronPDF

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

安装

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

您也可以使用 NuGet 包管理器安装 IronPDF,方法是在搜索栏中搜索 "ironpdf"。

C# Orderby(开发者的工作方式):图2 - 通过NuGet包管理器安装IronPDF

使用 IronPDF 生成 PDF

以下是使用 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
$vbLabelText   $csharpLabel

在这里,我们首先从sortedPeople生成一个HTML字符串,该字符串按照升序排序,并包含报告所需的所有格式。 然后我们使用IronPDF生成一个PDF文档。 我们使用RenderHtmlAsPdf方法将HTML字符串转换为PDF文档。

输出

PDF 中的输出结果如下。

C# Orderby(如何为开发人员工作):图3 - 前一个代码的输出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"
$vbLabelText   $csharpLabel

提供您的电子邮件以获取试用许可证。

结论

在C#中,OrderBy方法是一个根据各种标准对集合进行排序的多功能工具。 无论是按升序还是降序排序,按单一或多个标准排序,或使用自定义比较器,掌握OrderBy可以显著提高你的代码的清晰度和效率。

IronPDF 图书馆用于生成 PDF 文档一起组合,是生成精美格式和排序集合作为文档的绝佳组合。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C#开发工具包VS Code扩展(它如何为开发者工作)
下一步 >
MSTest C#(它对开发人员的工作原理)