首页 > 其他 > 详细

数组排序

时间:2014-03-14 23:34:13      阅读:754      评论:0      收藏:0      [点我收藏+]

            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

数组排序,布布扣,bubuko.com

数组排序

原文:http://mxlong.blog.51cto.com/8693674/1376254

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!