可以通過多種方式實現(xiàn)集合的自定義排序。以下是一些常見的方法:1. 使用 List<T>.Sort
方法與自定義比較器
List<T>
類提供了一個 Sort
方法,它允許傳遞一個 IComparer<T>
接口的實現(xiàn)來自定義排序邏輯。
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);
// 或者,可以實現(xiàn)更復(fù)雜的排序邏輯
}
}
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
方法與自定義鍵選擇器
如果不需要就地排序(即不修改原始集合),而是想創(chuàng)建一個已排序的新集合,可以使用 LINQ 的 OrderBy
方法。可以傳遞一個鍵選擇器函數(shù)來自定義排序邏輯。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. 實現(xiàn) IComparable<T>
接口
如果你的類本身就應(yīng)該有一個默認(rèn)的排序順序,可以讓該類實現(xiàn) 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();
注意,實現(xiàn) IComparable<T>
接口時也應(yīng)該重寫 Object.Equals
和 Object.GetHashCode
方法,以保持一致性,特別是在集合操作中(如使用哈希表時)。然而,對于排序目的,只實現(xiàn) IComparable<T>
就足夠了。
該文章在 2025/1/24 10:58:00 編輯過