跳至页脚内容
.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 简介

Discover IronPDF capabilities within the C# PDF library from 在C# PDF库中探索IronPDF的功能,这有助于读取和生成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包管理器安装IronPDF。

C# Orderby(开发人员如何使用):图2 - 通过NuGet包管理器安装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的步骤是什么?

可以使用NuGet包管理器在C#项目中安装IronPDF。可以在控制台中执行命令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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。