1. 程式人生 > >C#排序函式和自定義比較器

C#排序函式和自定義比較器

在C#中,要比較兩個陣列,可以呼叫

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

List等也有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 . . .
*/