C#集合排序指南:掌握自定义排序的多种方法
|
admin
2025年1月24日 10:20
本文热度 2203
|
可以通过多种方式实现集合的自定义排序。以下是一些常见的方法:1. 使用 List<T>.Sort 方法与自定义比较器
List<T> 类提供了一个 Sort 方法,它允许传递一个 IComparer<T> 接口的实现来自定义排序逻辑。
using System;using System.Collections.Generic;
public class Person{ public string Name { get; set; } public int Age { get; set; }}
public class PersonComparer : IComparer<Person>{ public int Compare(Person x, Person y) { return x.Age.CompareTo(y.Age);
// 如果想按名字排序,可以这样做: // return x.Name.CompareTo(y.Name);
// 或者,可以实现更复杂的排序逻辑 }}
class Program{ static void Main() { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 35 } };
people.Sort(new PersonComparer());
foreach (var person in people) { Console.WriteLine($"{person.Name}, {person.Age}"); } }}
2. 使用 LINQ 的 OrderBy 方法与自定义键选择器
如果不需要就地排序(即不修改原始集合),而是想创建一个已排序的新集合,可以使用 LINQ 的 OrderBy 方法。可以传递一个键选择器函数来自定义排序逻辑。using System;using System.Linq;
class Program{ static void Main() { var people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 35 } };
var sortedPeople = people.OrderBy(p => p.Age).ToList();
foreach (var person in sortedPeople) { Console.WriteLine($"{person.Name}, {person.Age}"); } }}
如果想按多个属性排序,可以使用 ThenBy 方法:
var sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();
3. 实现 IComparable<T> 接口
如果你的类本身就应该有一个默认的排序顺序,可以让该类实现 IComparable<T> 接口。这通常用于希望类的实例在任何情况下都按照相同的逻辑排序时。public class Person : IComparable<Person>{ public string Name { get; set; } public int Age { get; set; }
public int CompareTo(Person other) { if (other == null) return 1; return this.Age.CompareTo(other.Age); }}
people.Sort();
注意,实现 IComparable<T> 接口时也应该重写 Object.Equals 和 Object.GetHashCode 方法,以保持一致性,特别是在集合操作中(如使用哈希表时)。然而,对于排序目的,只实现 IComparable<T> 就足够了。
该文章在 2025/1/24 10:58:00 编辑过