c# ArrayList 的排序问题!

2009-01-19 20:10

c# ArrayList 的排序问题!

c# ArrayList 的排序问题!

我看见网上有人用IComparer接口实现ArrayLIst 的排序问题 ,于是自己写了个小例子,编译已经通过,和大家一块分享。有不足之处,望不吝指正。

1、建一个结构雇员结构

private struct Eployee{

    public string name;

    public int age;

    public string sex;

   }

2、新建3个"雇员"

Eployee ep1=new Eployee();

   ep1.name="小张";

   ep1.age=21;

   ep1.sex="男";

Eployee ep2=new Eployee();

   ep2.name="老李";

   ep2.age=43;

   ep2.sex="男";

Eployee ep3=new Eployee();

   ep3.name="施施";

   ep3.age=18;

   ep3.sex="男";

3、将3个"雇员" 加入"雇员列表";

 

ArrayList EmployeeList=new ArrayList();

   EmployeeList.Add(ep1);

   EmployeeList.Add(ep2);

   EmployeeList.Add(ep3);

好了一切准备就绪,现在希望EmployeeList中得"雇员"是按年龄排序

ArrayList 提供了我们现成排序方法Sort();

它有三个重载,不管使用哪一个,至少要你提供一个Comparer:IComparer;来告诉Sort方法 你对"雇员"们排序依据。

这个Comparer必须实现接口:System.Collections.IComparer ,该接口只有一个成员函数需要你去实现。

描述如下:

[C#]

int Compare(

   object x,

   object y

);

[JScript]

function Compare(

   x : Object,

   y : Object

) : int;

 

知道了这些那我们来实现一个吧

private class myEmployeeCompare:System.Collections.IComparer {

    public int Compare(object x,object y){

     return ((Eployee)x).age-((Eployee)y).age;

    }

   

   }

因为我们比较是“雇员”age,所以我们可以放心写实现语句

return ((Eployee)x).age-((Eployee)y).age;

myEmployeeCompare EmployeeCompare=new myEmployeeCompare();

 

ok现在我们可以对"雇员"们按年龄排序了

 

EmployeeList.Sort(EmployeeCompare);

 

 

源码:

using System; 
       using System.Collections;

 

class ArrayListT{
       private struct eployee
        {
                public string name;
               public int age;
                 public string sex;
         }
       ArrayListT(){}

class eployeeCompare: System.Collections.IComparer
        {

       public int Compare(object x,object y)
               {
                            return ((eployee)x).age - ((eployee)y).age;
                 }
      

}

public static void Main()
        {
                eployee ep1 = new eployee();
                ep1.name = "小张";
               ep1.age = 21;
               ep1.sex = "女";

          eployee ep2 = new eployee();
                ep2.name = "小李";
               ep2.age = 20;
               ep2.sex = "女";

          eployee ep3 = new eployee();
                ep3.name = "小王";
                 ep3.age = 26;
               ep3.sex = "女";

         ArrayList list = new ArrayList();
                list.Add(ep1);
                list.Add(ep2);
                 list.Add(ep3);

          eployeeCompare eployee = new eployeeCompare();
  
                 list.Sort(eployee);

          foreach (eployee ep in list)
                {
                       Console.WriteLine("the eployee's name is :{0} age is{1}",ep.name,ep.age);
                 }  
               Console.ReadLine();

     }
         }

posted on 2013-08-27 08:47  梦想的尾巴  阅读(469)  评论(0编辑  收藏  举报

导航