在 C# 中,可以通过多种方式实现对集合中元素的自定义排序,主要包括:
- 实现比较接口 IComparer
或 IComparable - 使用 List
.Sort 方法并传递自定义比较器 - 利用 LINQ 的 OrderBy 和 ThenBy 方法
- 自定义排序逻辑内联传递(如通过 Lambda 表达式)
示例代码
1. 使用IComparable接口
适用于对集合中的对象进行默认排序。
using System;
using System.Collections.Generic;
public class Person : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person other)
{
return Age.CompareTo(other.Age); // 按年龄排序
}
}
class Program
{
static void Main()
{
List people = new List
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
people.Sort();
foreach (var person in people)
{
Console.WriteLine($"{person.Name}, {person.Age}");
}
}
}
2. 使用IComparer接口
适用于多种排序规则。
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class AgeComparer : IComparer
{
public int Compare(Person x, Person y)
{
return x.Age.CompareTo(y.Age); // 按年龄排序
}
}
class Program
{
static void Main()
{
List people = new List
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
people.Sort(new AgeComparer());
foreach (var person in people)
{
Console.WriteLine($"{person.Name}, {person.Age}");
}
}
}
3. 使用 Lambda 表达式
简化排序逻辑。
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List numbers = new List { 3, 1, 4, 1, 5, 9 };
// 按降序排序
numbers.Sort((x, y) => y.CompareTo(x));
foreach (var number in numbers)
{
Console.WriteLine(number);
}
}
}
4. 使用 LINQ 的OrderBy和ThenBy方法
支持链式排序和延迟执行。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List names = new List { "Alice", "Bob", "Charlie" };
var sortedNames = names.OrderBy(name => name.Length).ThenBy(name => name);
foreach (var name in sortedNames)
{
Console.WriteLine(name);
}
}
}
总结
- IComparable
:适用于为对象定义默认排序。 - IComparer
:适用于需要多种排序规则的场景。 - Sort 方法结合 Lambda 表达式:适合简单的排序逻辑。
- LINQ 的 OrderBy 和 ThenBy:适合链式排序和复杂查询场景。
选择排序方式时应根据实际需求选择合适的实现方案。