簡體   English   中英

IComparable CompareTo(),如何比較多個對象屬性?

[英]IComparable CompareTo(), How do I compare multiple object properties?

我正在嘗試比較對象的多個屬性,但我的代碼只能比較 degree 屬性。 在 Visual Studio 中調試時,我的代碼似乎完全缺少 else 語句。 我將不勝感激任何提示。

class Student : IComparable 
{
    private string fName;
    private string lName;
    private string deg;
    private int gra;

    public Student(string firstName, string lastName, string degree, int grade)
    {
        fName = firstName;
        lName = lastName;
        deg = degree;
        gra = grade;
    }

    public override string ToString()
    {
        string var = lName + ", " + fName + " (" + deg + ") Grade: " + gra;
        return var;
    }

    public int CompareTo(object obj)
    {
        Student newStudent = obj as Student;

        if (this.deg.CompareTo(newStudent.deg) == 1)
        {
            return 1;
        }
        else if (this.deg.CompareTo(newStudent.deg) != 1)
        {
            return -1;
        }
        else //this is what my code is ignoring and not ordering by firstname as well
        {
            if (this.fName == newStudent.fName)
            {
                return 0;
            }
            else if (this.fName != newStudent.fName)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
}

您的問題的第一個答案(為什么else部分永遠不會被執行)已經得到回答,也就是說,沒有第三種可能的條件是1not 1

如果您嘗試按不同的屬性排序,例如,如果我們首先要按度數然后按fName排序,那么我們可以實現 IComparer-

class Student : IComparer<Student>{

    /*
    codes
   */


    public int Compare(Student student1, Student student2)
   {
          if(student1.deg.Equals(student2.deg))  //if both degrees are same
          {
              return string.Compare(student1.fName , student2.fName); // then compare fName
          }
          else
              return string.Compare(student1.deg , student2.deg);


   }
}

如果this.deg.CompareTo(newStudent.deg) == 1返回 1 ,如果this.deg.CompareTo(newStudent.deg) != 1則返回 -1 。 由於比較結果是或不等於 1,因此您永遠不會到達其余的 else。

因此,您的代碼應如下所示:

partial class Student : IComparable, IComparable<Student>
{
    public int CompareTo(object obj)
    {
        if (obj != null && obj.GetType() != GetType())
        {
            // From https://msdn.microsoft.com/en-us/library/system.icomparable.compareto(v=vs.110).aspx#Remarks
            // The parameter, obj, must be the same type as the class or value type that implements this interface; otherwise, an ArgumentException is thrown.
            throw new ArgumentException(string.Format("Object must be of type {0}", GetType()));
        }
        return CompareTo((Student)obj);
    }

    public int CompareTo(Student newStudent)
    {
        if (object.ReferenceEquals(this, newStudent))
            return 0;
        else if (newStudent == null)
            // From https://msdn.microsoft.com/en-us/library/43hc6wht(v=vs.110).aspx#Remarks
            // By definition, any object compares greater than null, and two null references compare equal to each other.
            return 1;

        var cmp = this.deg.CompareTo(newStudent.deg);
        if (cmp != 0)
            return cmp;

        cmp = this.fName.CompareTo(newStudent.fName);
        if (cmp != 0)
            return cmp;

        // Compare additional members as required, return the first nonzero member comparison.

        // Finally return 0 if all member comparisons returned 0.
        return 0;
    }
}

筆記:

在你的代碼中

if (this.deg.CompareTo(newStudent.deg) == 1)
{
    // do something
}
else if (this.deg.CompareTo(newStudent.deg) != 1)
{
    // do something
}
else 
{
    // do something
}

永遠不會到達 else 語句,因為結果可能等於 1 或不等於。 並且您只檢查“deg”值。 例如,您可以像這樣檢查它們是否相等:

public int CompareTo(object obj)
{
    if (obj == null)
    {
        return -1;
    }
    Student newStudent = obj as Student;
    // are equal
    if (deg.CompareTo(newStudent.deg) == 0 && 
        gra.CompareTo(newStudent.gra) == 0 &&
        lName.CompareTo(newStudent.lName) == 0 &&
        fName.CompareTo(newStudent.fName) == 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM