跳转到内容

C Sharp LINQ 排序

来自代码酷

C# LINQ排序[编辑 | 编辑源代码]

LINQ(Language Integrated Query)是.NET框架中强大的查询功能,而排序是数据处理中最常见的操作之一。在C#中,LINQ提供了多种排序方法,允许开发者以简洁、灵活的方式对数据进行排序。本文将详细介绍LINQ中的排序操作,包括基本排序、多条件排序、自定义排序等,并提供实际应用示例。

概述[编辑 | 编辑源代码]

LINQ排序操作主要通过OrderByOrderByDescendingThenByThenByDescending方法实现。这些方法允许开发者对集合(如数组、列表或数据库查询结果)进行升序或降序排列。LINQ排序是延迟执行的,只有在实际遍历结果时才会执行排序操作。

基本排序方法[编辑 | 编辑源代码]

  • OrderBy:按指定键升序排列。
  • OrderByDescending:按指定键降序排列。
  • ThenBy:在已排序的基础上,按第二个键升序排列(用于多条件排序)。
  • ThenByDescending:在已排序的基础上,按第二个键降序排列。

基本排序示例[编辑 | 编辑源代码]

以下示例展示如何使用OrderByOrderByDescending对整数列表进行排序。

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

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3 };

        // 升序排序
        var ascendingOrder = numbers.OrderBy(n => n);
        Console.WriteLine("升序排序:");
        foreach (var num in ascendingOrder)
            Console.WriteLine(num);

        // 降序排序
        var descendingOrder = numbers.OrderByDescending(n => n);
        Console.WriteLine("\n降序排序:");
        foreach (var num in descendingOrder)
            Console.WriteLine(num);
    }
}

输出:

升序排序:
1
2
3
5
8
9

降序排序:
9
8
5
3
2
1

多条件排序[编辑 | 编辑源代码]

当需要按多个条件排序时,可以使用ThenByThenByDescending。以下示例对一组学生按姓名升序和年龄降序排序:

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

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 22 },
            new Student { Name = "Alice", Age = 18 },
            new Student { Name = "Charlie", Age = 20 }
        };

        // 先按Name升序,再按Age降序
        var sortedStudents = students
            .OrderBy(s => s.Name)
            .ThenByDescending(s => s.Age);

        Console.WriteLine("多条件排序结果:");
        foreach (var student in sortedStudents)
            Console.WriteLine($"Name: {student.Name}, Age: {student.Age}");
    }
}

输出:

多条件排序结果:
Name: Alice, Age: 20
Name: Alice, Age: 18
Name: Bob, Age: 22
Name: Charlie, Age: 20

自定义排序[编辑 | 编辑源代码]

在某些情况下,可能需要自定义排序逻辑。可以通过实现IComparer<T>接口或使用Lambda表达式来实现。以下示例演示如何按字符串长度排序:

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

class Program
{
    static void Main()
    {
        List<string> words = new List<string> { "apple", "banana", "cherry", "date" };

        // 按字符串长度升序排序
        var sortedByLength = words.OrderBy(w => w.Length);

        Console.WriteLine("按长度排序:");
        foreach (var word in sortedByLength)
            Console.WriteLine(word);
    }
}

输出:

按长度排序:
date
apple
banana
cherry

实际应用案例[编辑 | 编辑源代码]

假设有一个电子商务网站,需要按价格和销量对商品排序:

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

class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Sales { get; set; }
}

class Program
{
    static void Main()
    {
        List<Product> products = new List<Product>
        {
            new Product { Name = "Laptop", Price = 999.99m, Sales = 150 },
            new Product { Name = "Phone", Price = 699.99m, Sales = 300 },
            new Product { Name = "Tablet", Price = 499.99m, Sales = 200 }
        };

        // 按价格升序,销量降序排序
        var sortedProducts = products
            .OrderBy(p => p.Price)
            .ThenByDescending(p => p.Sales);

        Console.WriteLine("商品排序结果:");
        foreach (var product in sortedProducts)
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}, Sales: {product.Sales}");
    }
}

输出:

商品排序结果:
Name: Tablet, Price: 499.99, Sales: 200
Name: Phone, Price: 699.99, Sales: 300
Name: Laptop, Price: 999.99, Sales: 150

性能考虑[编辑 | 编辑源代码]

LINQ排序的时间复杂度通常为O(n log n),与快速排序或归并排序类似。对于大型数据集,建议:

  • 使用AsParallel()进行并行排序(PLINQ)。
  • 避免频繁排序,尽量缓存排序结果。

总结[编辑 | 编辑源代码]

  • LINQ提供了灵活的排序方法(OrderByOrderByDescendingThenByThenByDescending)。
  • 支持多条件排序和自定义排序逻辑。
  • 适用于集合、数据库查询等多种数据源。
  • 在实际开发中,排序是数据处理的核心操作之一,合理使用LINQ排序能显著提升代码可读性和效率。

通过本文的学习,您应能掌握C# LINQ排序的基本和高级用法,并能在实际项目中灵活应用。