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

发布于 2024-08-06 14:26:28 字数 371 浏览 2 评论 0原文

如何在两个字符串字段上实现 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);
});

How do I implement the IComparable Interface on two string fields?

Using the Person class example below. If Person objects are added to a list. How do I sort the list based on Surname first THEN Forename?

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

Something like? :

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

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

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

发布评论

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

评论(2

梦中楼上月下 2024-08-13 14:26:28

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

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

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

编辑 正如 Mark 评论的那样,您可能决定您需要检查空值。如果是这样,您应该决定是否应将 null 排序到顶部或底部。像这样的东西:

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

Or you could sort a list like this:

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

Alternatively you could have Person implement IComparable<Person> with this method:

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

EDIT As Mark commented, you might decide you need to check for nulls. If so, you should decide whether nulls should be sorted to the top or bottom. Something like this:

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
驱逐舰岛风号 2024-08-13 14:26:28

试试这个?

int surnameComparison = p1.Surname.CompareTo(p2.Surname);

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

Try this?

int surnameComparison = p1.Surname.CompareTo(p2.Surname);

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