自定义排序(三个字段上的IComparer) [英] Custom Sorting (IComparer on three fields)
本文介绍了自定义排序(三个字段上的IComparer)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含三个字段的人类,分别是标题,名称,性别,我想为其创建一个自定义排序,以便先按标题,名称再按性别升序对它进行排序:
I have a person class with three fields, Title, Name, Gender and I would like to create a Custom Sort for it to sort it first by Title, then by Name and then by Gender ascending:
public class SortPerson : IComparer
{
public int Compare(object x, object y)
{
(…)
}
}
我知道该怎么做只有一个要比较的变量:
但是我将如何继续进行三个操作?
I know how to do this for only one variable to compare against: But How would I have to proceed with three?
public class SortPerson : IComparer
{
int IComparer.Compare(object a, object b)
{
Person p1=(Person)a;
Person p2=(Person)b;
if (p1.Title > p2.Title)
return 1;
if (p1.Title < p2.Title)
return -1;
else
return 0;
}
}
非常感谢,
推荐答案
//Assuming all the fields implement IComparable
int result = a.field1.CompareTo(b.field1);
if (result == 0)
result = a.field2.CompareTo(b.field2);
if (result == 0)
result = a.field3.CompareTo(b.field3);
return result;
这篇关于自定义排序(三个字段上的IComparer)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文