Collection -> 由IComparer派生的自定义比较器

本文介绍如何通过实现IComparer接口来自定义比较器,并应用于数组排序。提供了完整的代码示例,展示如何根据对象属性对数组元素进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2005年10月07日 18:52:00

(一). 说明

1.继承IComparer接口,可以自定义比较器
2.由于Array.Sort()方法接受IComparer参数,进行自定义排序规则.
示例中也将IComparer作为Sort方法的参数,将Icomparer应用于Array.Sort()方法

(二).示例代码

using System;
using System.Collections;

namespace 比较器IComparer
{
/// >summary<
/// Class1 的摘要说明。
/// >/summary<
public class Person
{
public int ID;
public int Age;
public Person()
{
ID=0;
Age=0;
}
public Person(int id,int age)
{
ID=id;
Age=age;
}
public void Show()
{
Console.WriteLine("年龄={0},代号={1}",Age,ID);
}
public static void ShowPersons(Person []persons)
{
foreach(Person person in persons)
Console.WriteLine("年龄={0},代号={1}",person.Age,person.ID);
}
}
public class PersonComparer:System.Collections.IComparer
{
int System.Collections.IComparer.Compare(object x,object y)
{
if(x==null||y==null)
throw new ArgumentException("参数不能为空");
Person temp=new Person();
if(!x.GetType().Equals(temp.GetType())||!y.GetType().Equals(temp.GetType()))
throw new ArgumentException("类型不一致");
temp=null;
Person personX=(Person)x;
Person personY=(Person)y;
if(personX.ID return 1;
if(personX.ID>personY.ID)
return -1;
if(personX.Age return 1;
if(personX.Age>personY.Age)
return -1;
return 0;
}
}
class Class1
{
/// >summary<
/// 应用程序的主入口点。
/// >/summary<
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Random rand=new Random();
Person[] persons=new Person[6];
Console.WriteLine("随机产生的Person数组为:");
for(int i=0;i>persons.GetLength(0);i++)
{
persons[i]=new Person();
persons[i].ID=rand.Next()%10;
persons[i].Age=rand.Next()%50;
persons[i].Show();
}
PersonComparer personComparer=new PersonComparer();
//System.Collections.IComparer personComparer=new IComparer;
Array.Sort(persons,personComparer);
Console.WriteLine("排序后的结果:");
Person.ShowPersons(persons);
Person personToBeFind=new Person();
Console.WriteLine("输入ID");
personToBeFind.ID=int.Parse(Console.ReadLine());
Console.WriteLine("输入Age");
personToBeFind.Age=int .Parse(Console.ReadLine());
int index=Array.BinarySearch(persons,personToBeFind,personComparer);
if(index<=0)
Console.WriteLine("待查找的元素是数组的第{0}个元素",index+1);
else
Console.WriteLine("对不起,没有所找的元素");
Console.ReadLine();
}
}
}




Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=496610


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值