代码之家  ›  专栏  ›  技术社区  ›  Alex Gordon

如何实现IComparable接口?

  •  64
  • Alex Gordon  · 技术社区  · 14 年前

    我正在用类的实例填充数组:

    BankAccount[] a;
    . . .
    
    a = new BankAccount[]
    {
        new BankAccount("George Smith", 500m),
        new BankAccount("Sid Zimmerman", 300m)
    };
    

    一旦我填充了这个数组,我想按余额对它进行排序。为了做到这一点,我想能够检查每个元素是否可以使用 IComparable .
    我需要使用接口来实现这一点。到目前为止,我有以下代码:

    public interface IComparable
    {
        decimal CompareTo(BankAccount obj);
    }
    

    但我不确定这是否是正确的解决方案。有什么建议吗?

    6 回复  |  直到 14 年前
        1
  •  117
  •   Adam Szabo    11 年前

    您不应该定义可比较的自己。它已被定义。

    相反,你需要 实施 我比较你的 BankAccount 班级。

    你定义的地方 class BankAccount ,确保它实现IComparable接口

    然后写 BankAccout.CompareTo 比较两个对象的余额。


    编辑

    public class BankAccount : IComparable<BankAccount>
    {
        [...]
    
        public int CompareTo(BankAccount that)
        {
            if (this.Balance >  that.Balance) return -1;
            if (this.Balance == that.Balance) return 0;
            return 1;
        }
    }
    

    编辑2 为了展示杰弗里·L·惠特利奇的好答案:

    public class BankAccount : IComparable<BankAccount>
    {
        [...]
    
        public int CompareTo(BankAccount that)
        {
            return this.Balance.CompareTo(that.Balance);
        }
    }
    
        2
  •  15
  •   Eric Lippert    14 年前

    你想吗 破坏性的 对数组排序?也就是说,是否要实际更改数组中项目的顺序?或者,您只是想要一个特定顺序的项目列表,而不破坏原始顺序?

    我会建议,做后者几乎总是更好的。考虑使用LINQ进行非破坏性排序。(并考虑使用比“a”更有意义的变量名。)

    BankAccount[] bankAccounts = { whatever };
    var sortedByBalance = from bankAccount in bankAccounts 
                          orderby bankAccount.Balance 
                          select bankAccount;
    Display(sortedByBalance);
    
        3
  •  14
  •   Lou Franco    14 年前

    IComparable .NET中已存在具有此CompareTo定义的

    int CompareTo(Object obj)
    

    你不应该创建接口——你应该实现它。

    public class BankAccount : IComparable {
    
        int CompareTo(Object obj) {
               // return Less than zero if this object 
               // is less than the object specified by the CompareTo method.
    
               // return Zero if this object is equal to the object 
               // specified by the CompareTo method.
    
               // return Greater than zero if this object is greater than 
               // the object specified by the CompareTo method.
        }
    }
    
        4
  •  10
  •   Matt Greer    14 年前

    另一种选择是使用LINQ和Skip实现IComparable:

    BankAccount[] sorted = a.OrderBy(ba => ba.Balance).ToArray();
    
        5
  •  5
  •   Marc Gravell    14 年前

    已经有了 IComparable<T> 但是你最好两者都支持 i可比较<t> IComparable . 使用内置 Comparer<T>.Default 通常是更容易的选择。 Array.Sort 例如,将接受这样的比较器。

        6
  •  2
  •   Zain Shaikh    11 年前

    如果你只需要把这些分类 BankAccounts 使用 LINQ 像下面一样

    BankAccount[] a = new BankAccount[]
    {
        new BankAccount("George Smith", 500m),
        new BankAccount("Sid Zimmerman", 300m)
    };
    
    a = a.OrderBy(bank => bank.Balance).ToArray();
    
    推荐文章