1

CompareTo 方法逻辑如何在 List 排序函数中工作。

public class person : IComparable
{
    string firstName;
    string lastName;

    public int CompareTo(object obj)
    {
        person otherPerson = (person)obj;
        if (this.lastName != otherPerson.lastName)
            return this.lastName.CompareTo(otherPerson.lastName);
        else
            return this.firstName.CompareTo(otherPerson.firstName);
    }

    public person(string _firstName, string _lastName)
    {
        firstName = _firstName;
        lastName = _lastName;
    }

    override public string ToString()
    {
        return firstName + " " + lastName;
    }
}

List<person> l = new List<person>();
l.Add(new person("Mark", "Hanson"));
l.Add(new person("Kim", "Akers"));
l.Add(new person("Zsolt", "Ambrus"));

l.Sort();

foreach (person p in l)
    Console.WriteLine(p.ToString());
4

2 回答 2

4

当您在通用列表(在您的情况下为 List)上调用Sort 方法时,在幕后,Sort 的实现将检查列表(person类)的类型是否实现了IComparable接口,如果实现了,它将调用CompareTo成员执行列表元素之间的比较以执行排序。类实现 IComparable的事实person被解释为一个“契约”,它指定person该类将有一个名为 CompareTo 的方法。

Sort 的实现可以使用如下代码片段与列表中的元素进行比较:

T aPerson;
T anotherPerson;
int compareResult;

if(aPerson is IComparable)
{
    compareResult = (aPerson as IComparable).CompareTo(anotherPerson);
}

CompareTo 方法始终将调用它的对象与参数进行比较,返回值的含义始终相同:

* if the two objects are "equal", it returns 0
* if the object you are comparing to is "less than" - in a sorted list it goes before - the object you are invoking CompareTo on, it returns -1
* if the object you are comparing to is "greater than" - in a sorted list it goes after - the object you are invoking CompareTo on, it returns +1

在内部,Sort 方法使用优化的 QuickSort 来实际执行排序,但为了更容易理解,下面是一个实现冒泡排序的示例,它说明了在调用 IComparable 接口方面发生的幕后情况:

// assume the Sort invokes this naive bubble sort 
// on the internal backing array of the list
void InternalBubbleSort(T[] backingArray) 
{
  var swapped = false;
  do {
    swapped = false;
    for(int i = 0; i < Length - 1; i++) {
      if (backingArray[i].CompareTo(backingArray[i+1]) > 0) {
        T temp = backingArray[i];
        backingArray[i] = backingArray[i+1];
        backingArray[i+1] = temp;
        swapped = true;
      }
    }while(swapped);
}
于 2010-10-15T14:57:12.143 回答
2

它按姓氏排序,然后是名字。

如果两个人的姓氏相同,则该if语句最终将按名字进行比较。
否则,它将按姓氏进行比较。

于 2010-10-15T14:52:27.863 回答