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

时间:2010-10-15 14:46:58

标签: c# .net list sorting icomparable

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());

2 个答案:

答案 0 :(得分:4)

当您在通用列表(在您的情况下为List)上调用Sort method时,在后台,Sort的实现将检查列表的类型(person类)是否实现了IComparable接口,如果是,它将调用CompareTo成员来执行列表元素之间的比较以执行排序。 person类实现IComparable的事实被解释为“契约”,它指定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来实际执行排序,但是为了更容易理解,这里是一个实现bubble sort的例子,它说明了在调用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);
}

答案 1 :(得分:2)

按名字排序,然后是名字。

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