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

发布于 2024-09-27 14:55:13 字数 889 浏览 4 评论 0原文

CompareTo 方法逻辑在列表排序函数中的工作原理。

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

How CompareTo method logic works in List sort function.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东风软 2024-10-04 14:55:13

当您在通用列表(您的列表中的情况),在幕后,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);
}

When you invoke the Sort method on a generic list (List in your case), behind the scenes, the implementation of Sort will check if the type of the list (the person class) implements the IComparable interface, and if it does it will invoke the CompareTo member to perform comparisons between elements of the list to perform the sort. The fact that the person class implements IComparable is interpreted as a "contract" that specifies that the person class will have a method called CompareTo.

The implementation of Sort can use a snippet such as the following to compare to elements of the list:

T aPerson;
T anotherPerson;
int compareResult;

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

The CompareTo method always compares the object it is invoked on to the parameter and the meaning of the return value is always the same:

* 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

Internally, the Sort method uses an optimized QuickSort to actually perform the sort but to make it easier to follow, here's an example of implementing bubble sort which illustrates what happens behind the scenes in terms of invoking the IComparable interface:

// 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);
}
吻风 2024-10-04 14:55:13

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

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

It sorts by last name, then first name.

If two people have the same last name, the if statement will end up comparing by first name.
Otherwise, it will compare by last name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文