【问题标题】:implementing the IComparable Interface on two string fields在两个字符串字段上实现 IComparable 接口
【发布时间】:2009-10-06 12:12:57
【问题描述】:

如何在两个字符串字段上实现 IComparable 接口?

使用下面的 Person 类示例。如果将 Person 对象添加到列表中。如何根据姓氏优先然后名字对列表进行排序?

Class Person
{
    public string Surname { get; set; }
    public string Forname { get; set; }
}

类似的东西? :

myPersonList.Sort(delegate(Person p1, Person p2)
{
    return p1.Surname.CompareTo(p2. Surname);
});

【问题讨论】:

    标签: c# compare


    【解决方案1】:

    或者你可以像这样对列表进行排序:

    myPersonList.Sort(delegate(Person p1, Person p2)
    {
        int result = p1.Surname.CompareTo(p2.Surname);
        if (result == 0)
            result = p1.Forname.CompareTo(p2.Forname);
        return result;
    });
    

    或者,您可以让Person 使用此方法实现IComparable<Person>

    public int CompareTo(Person other)
    {
        int result = this.Surname.CompareTo(other.Surname);
        if (result == 0)
            result = this.Forname.CompareTo(other.Forname);
        return result;
    }
    

    EDIT 正如 Mark 所说,您可能决定需要检查空值。如果是这样,您应该决定是否应该将空值排序到顶部或底部。像这样的:

    if (p1==null && p2==null)
        return 0; // same
    if (p1==null ^ p2==null)
        return p1==null ? 1 : -1; // reverse this to control ordering of nulls
    

    【讨论】:

    • 检查 .Surname 中的空值怎么样?
    • @Tymec,只需重复用于 p1 和 p2 的相同模式,但使用 p1.Surname 和 p2.Surname。
    【解决方案2】:

    试试这个?

    int surnameComparison = p1.Surname.CompareTo(p2.Surname);
    
    if (surnameComparison <> 0)
      return surnameComparison;
    else
      return p1.Forename.CompareTo(p2.Forename);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      相关资源
      最近更新 更多