【c#高级编程】数组和元组:通过IComparable接口实现自定义类的数组元素排序

本文为 C#高级编程(第十版) 读书笔记,整理学过的知识,便于忘记后重新拾起。

通过IComparable接口实现自定义类的数组元素排序

  1. 通过继承Icomparable接口实现类排序
    Array类使用Quicksort算法对数组中的元素进行排序。Sort()方法需要数组中的元素实现Icomparable接口。
    Icomparable接口只定义了一个方法CompareTo(),如果比较对象相等返回0,如果实例应该排在参数的前面返回小于0的值,否则返回大于0的值
    示例:
//自定义类
public class Person{
	public string FirstName;
	public string LastName;
}
//拓展后的自定义类
Public class Person:IComparable<Person>
{
	public string FirstName;
	public string LastName;
	
	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;
	}
}
//使用
//声明一个数组
Person[] persons={
....
....
}
//排序
Array.Sort(persons);

2.通创建一个新类IComparer继承实现排序功能

如果Person对象的排序方式不同,或者不能修改在数组中作为元素的类,那么可以实现IComparer接口或IComparer接口。这两个接口定义了Compare(),要比较的类必须实现这两个接口之一。
代码如下:

//用于比较的枚举参数
public enum PersonCompareType
{
	FirstName,
	LastName.
}
//拓展Person比较功能的类
public class PersonComparer:IComparer<Person>
{
	private PersonComparerType _compareType;
	public PersonComparer(PersonComparerType comparerType)
	{
		_compareType=comparerType;
	}
	public int Compare(Person x,Persony)
	{
		if(x==null&&y==null)
		{
			return 0;
		}
		
		if(x==null)
		{
			return 1;
		}
		
		if(y==null)
		{
			return -1;
		}
		switch(_compareType)
		{
			case PersonCompareType.FirstName:
				return string.Compaer(x.FirstName,y.FirstName);
			case PersonCompareType.LastName:
				return string.Compaer(x.LastName,y.LastName);
			default:
				throw new ArgumentException("unexpected compare type");
		}
	}
}
//使用
Array.sort(persons,new PersonComparer(PersonCompareType.FirstName));

3.通过委托参数实现排序功能(待补充…)
Array类还提供了Sort方法需要将一个委托作为参数。这个参数可以传递给方法,从而不依赖IComparable或者ICmparer接口实现类的比较排序。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JousonRen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值