C# 自定义比较器

                                                           C# 自定义比较器

在C#中,要比较两个数组,可以调用

System.Array.Sort(...)方法

 

有两种方式可以为自己的类提供排序;

 

1.类实现接口 IComparable

2.创建比较器类,该类实现接口IComparer

 

第二种方法的优点是,你可以在不修改已有的类,创建自己的比较器类,而且能实现比第一种方法更加灵活的方式;

 

//rorger,2011 //IComparable & IComparer //using Sysem.Collections required using System; using System.Linq; using System.Text; using System.Collections; namespace AnimalCompare { class Program { public class Animal:IComparable { private string name; private int age; public string Name { get{return name;} set{name=value;} } public int Age { get { return age; } set{age=value;} } public Animal(string name,int age ) { this.name = name; this.age = age; } public int CompareTo(Object obj) { Animal other = obj as Animal; int result = name.CompareTo(other.name); if (result ==0) { result = age.CompareTo(other.age); } return result; } public override string ToString() { return string.Format("{0},{1}", name, age); } } public class AnimalComparer:IComparer { public int Compare(object lhs,object rhs) { Animal aniLhs = lhs as Animal; Animal aniRhs = rhs as Animal; int result = aniLhs.Age.CompareTo(aniRhs.Age); if (result == 0) { result = aniLhs.Name.CompareTo(aniRhs.Name); } return result; } } static void Main(string[] args) { Animal[] animals = new Animal[]{ new Animal("ElephantBig",5), new Animal("ElephantBig",3), new Animal("ElephantNano",1) }; foreach (Animal animal in animals) { Console.WriteLine(animal); } Console.WriteLine("/nAfter soring..."); Array.Sort(animals); foreach (Animal animal in animals) { Console.WriteLine(animal); } Console.WriteLine("/nUsing IComparer..."); Array.Sort(animals, new AnimalComparer()); foreach (Animal animal in animals) { Console.WriteLine(animal); } } } } /* *ouput: ElephantBig,5 ElephantBig,3 ElephantNano,1 After soring... ElephantBig,3 ElephantBig,5 ElephantNano,1 Using IComparer... ElephantNano,1 ElephantBig,3 ElephantBig,5 Press any key to continue . . . */

你可能感兴趣的:(String,object,C#,Class)