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

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

使用下面的Person类示例.如果将Person对象添加到列表中.如何根据Surname first THEN Forename对列表进行排序?

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

解决方法

或者你可以像这样排序一个列表:
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;
}

编辑正如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

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么