使用默认比较器
如果集合中的元素实现了 IComparable<T>
接口,List<T>
会使用该接口的默认实现来排序。
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };
numbers.Sort();
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
使用自定义比较器
如果需要自定义排序规则,可以实现 IComparer<T>
接口,并在排序时传入该接口的实现。
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> words = new List<string> { "apple", "orange", "banana", "grape" };
words.Sort(new CustomComparer());
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
// 逆序排序
return y.CompareTo(x);
}
}
使用 Lambda 表达式
可以通过传入一个 Lambda 表达式来定义排序规则。
using System;
using System.Collections.Generic;
public class Program
{
public 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((x, y) => x.Age.CompareTo(y.Age));
foreach (Person person in people)
{
Console.WriteLine($"{person.Name} - {person.Age}");
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
使用 LINQ
除了 List<T>
的 Sort
方法,还可以使用 LINQ 的 OrderBy
和 OrderByDescending
方法来对集合进行排序。
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };
var sortedNumbers = numbers.OrderBy(n => n).ToList();
foreach (int number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
这些示例展示了如何使用不同的方式对集合泛型进行排序。根据具体需求,可以选择适合的排序方法。