在两个字符串字段上实现 IComparable 接口
如何在两个字符串字段上实现 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者您可以像这样对列表进行排序:
或者您可以使用以下方法让
Person
实现IComparable
:编辑 正如 Mark 评论的那样,您可能决定您需要检查空值。如果是这样,您应该决定是否应将 null 排序到顶部或底部。像这样的东西:
Or you could sort a list like this:
Alternatively you could have
Person
implementIComparable<Person>
with this method: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:
试试这个?
Try this?