数组排序

            int [] ly={1,4,5,6,78,2,3}

Array.sotr(ly);

输出结果:1,2,3,4,5,6,78

 

sort()方法,派生自IComparer接口。如果是泛型类数组如何排序呢?

 

public class Person

{

    public string firstName{set;get;}

    public string lastName{set;get;}

}

 

public Enum PersonType{ firstName,lastName}

 

public class PersonComparer : IComparer<Person>

{

    PersonType pt;

    public PersonComparer(PersonType p){pt=p;}

 

    public int Comparer(Person a,Person b)

    switch(pt)

    {

        case PersonType.firstName:

                    return a.firstName.CompareTo(b.firstName);

        case PersonType.lastName:

                    return a.lastName.CompareTo(b.lastName);

        default:

                    throw new Exception("Error!");

    }

}

 

用方法测试下:

Person [] pl={new Person(){firstName="g",lastName=""},

                        new Person(){firstName="s",lastName=""},

                        new Person(){firstName="d",lastName=""},

                        new Person(){firstName="v",lastName=""},

                        new Person(){firstName="c",lastName=""}

}

 

Array.sort( pl , new PersonComparer(PersonType.firstName) );

 

输出结果:c , d ,g ,s,v

你可能感兴趣的:(数组排序)