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

(一). 说明

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

(二).示例代码

using System;
using System.Collections;

namespace 比较器IComparer
{
///

1<summary>   
2/// Class1 的摘要说明。   
3/// </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>personY.ID)
return 1;
if(personX.ID

 1<persony.id) -1;="" if(personx.age="" return="">personY.Age)   
 2return 1;   
 3if(personX.Age<persony.age) -1;="" 0;="" <summary="" class="" class1="" return="" {="" }="">   
 4/// 应用程序的主入口点。   
 5///    
 6[STAThread]   
 7static void Main(string[] args)   
 8{   
 9//   
10// TODO: 在此处添加代码以启动应用程序   
11//   
12Random rand=new Random();   
13Person[] persons=new Person[6];   
14Console.WriteLine("随机产生的Person数组为:");   
15for(int i=0;i<persons.getlength(0);i++) .parse(console.readline());="" array.sort(persons,personcomparer);="" console.writeline("排序后的结果:");="" console.writeline("输入age");="" console.writeline("输入id");="" icomparer;="" if(index="" index="Array.BinarySearch(persons,personToBeFind,personComparer);" int="" person="" person();="" person.showpersons(persons);="" personcomparer="new" personcomparer();="" persons[i]="new" persons[i].age="rand.Next()%50;" persons[i].id="rand.Next()%10;" persons[i].show();="" persontobefind="new" persontobefind.age="int" persontobefind.id="int.Parse(Console.ReadLine());" system.collections.icomparer="" {="" }="">=0)   
16Console.WriteLine("待查找的元素是数组的第{0}个元素",index+1);   
17else   
18Console.WriteLine("对不起,没有所找的元素");   
19Console.ReadLine();   
20}   
21}   
22} 
23
24谢谢阅读!</persons.getlength(0);i++)></persony.age)></persony.id)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus