IComparable和IComparer是.NET中比较对象的标准方式。具体差别如下:
IComparable:在要比较的对象的类中单独实现,可该对象和另外一个对象。该接口包含CompareTo()方法,该方法接受要比较类的实例对象。参数对象与实例相等,返回0,参数对象排在实例前面,返回-1,参数对象排在实例后面,返回1。
IComparer:在一个单独的类中实现,可比较任意两个对象。该接口包含一个Compare()方法,接受两个对象。若两个对象相等,返回0,第一个对象排在第二个对象后面返回1,第一个对象排在第二个对象前面-1。
一般来说,IComparable给出默认比较代码,使用其他类给出默认比较代码
注:(1)null对象永远排在最后
(2)如果想按照由大到小的顺序排序,Compare()或CompareTo()返回值乘-1即可
IComparable的实现
public class Person: IComparable<Person>
{
public string FirstName;
public string LastName;
public int Age;
public Person(string firstName,string lastName,int age)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
}
public int CompareTo(Person other)
{
if(other==null)
{
return -1;
}
int result = string.Compare(this.LastName, other.LastName);
if(result==0)
{
result = string.Compare(this.FirstName, other.FirstName);
}
return result;
}
public override string ToString()
{
return string.Format("{0} {1} {2}", this.LastName, this.FirstName, this.Age);
}
}
IComparer的实现
public enum CompareType
{
FirstName,LastName,Age
}
//在一个单独的类中实现IComparer
public class PersonComparer:IComparer<Person>
{
public CompareType compareType;
public PersonComparer(CompareType n_compareType)
{
this.compareType = n_compareType;
}
public int Compare(Person p1,Person p2)
{
if(p1==null&&p2==null)
{
return 0;
}
if (p1 == null)
{
return 1;
}
if (p2 == null)
{
return -1;
}
switch(compareType)
{
case CompareType.LastName:
return string.Compare(p1.LastName, p2.LastName);
case CompareType.FirstName:
return string.Compare(p1.LastName, p2.LastName);
case CompareType.Age:
//此处按照从大到小顺序排,返回值乘-1
if (p1.Age < p2.Age)
{
return 1;
}
else if (p1.Age < p2.Age)
{
return -1;
}
else
{
return 0;
}
default:
throw new ArgumentException("未定义排序类型");
}
}
}
运行实例
static void Main(string[] args)
{
Person[]personSet = new Person[] { new Person("Xue","Bai",34), new Person("Na", "Bai", 21) ,
new Person("Ping","Li",28),new Person("Qiang","Li",37),new Person("Fang","Wu",22),
new Person("Lei","Wang",25)};
Console.WriteLine("默认排序");
Array.Sort(personSet);
for(int i=0;i<personSet.Length;i++)
{
Console.WriteLine(personSet[i].ToString());
}
Console.WriteLine("按照年龄由大到小排序");
Array.Sort(personSet, new PersonComparer(CompareType.Age));
for (int i = 0; i < personSet.Length; i++)
{
Console.WriteLine(personSet[i].ToString());
}
Console.ReadKey();
}
运行结果:
更多精彩文章,请微信搜索公众号:码农修炼秘籍