Array类的Sort()方法

Array类实现了数组中元素的冒泡排序。Sort()方法要求数组中的元素实现IComparable接口。如System.Int32

和System.String实现了IComparable接口,所以下面的数组可以使用Array.Sort()。

 C# Code 
1
2
3
4
5
6
string[] names = {  "Lili",  "Heicer",  "Lucy" };
Array.Sort(names);
foreach ( string n  in names)
    {
        Console.WriteLine(n);
    }
输出排序后的数组:

如果对数组使用定制的类,就必须实现IComparable接口。这个借口定义了一个方法CompareTo()。

Person类:

 C# Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public  class Person : IComparable
{
     public Person() { }
     public Person( string name,  string sex)
    {
         this.Name = name;
         this.Sex = sex;
    }
     public  string Name;
     public  string Sex;

     public  override  string ToString()
    {
         return  this.Name +  " " +  this.Sex;
    }
     #region IComparable 成员
     public  int CompareTo( object obj)
    {
        Person p = obj  as Person;
         if (p ==  null)
            {
                 throw  new NotImplementedException();
            }
         return  this.Name.CompareTo(p.Name);
    }
     #endregion
}
这里就可以对Person对象数组排序了:

 C# Code 
1
2
3
4
5
6
7
8
9
10
11
Person[] persons =
{
     new Person( "Lili",  "Female"),
     new Person( "Heicer",  "Male"),
     new Person( "Lucy",  "Female")
};
Array.Sort(persons);
foreach (Person p  in persons)
    {
        Console.WriteLine(p);
    }
排序后的结果:


如果Person对象的排序方式不同,或者不能修改在数组中用作元素的类,就可以执行ICompare接口。这个接口定义了Compare()方法。ICompare接口必须要独立于要比较的类。这里定义PersonCompare类

PersonCompare类:
 C# Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public  class PersonComparer: IComparer
{
     public PersonComparer() { }
     #region IComparer 成员
     public  int Compare( object x,  object y)
    {
        Person p1 = x  as Person;
        Person p2 = y  as Person;
         if (p1 ==  null || p2 ==  null)
            {
                 throw  new ArgumentException( "Person为空");
            }
         return p1.Name.CompareTo(p2.Name);
    }
     #endregion
}
现在,可以将一个PersonComparer对象传送给Array.Sort()方法的第二个变元。

 C# Code 
1
Array.Sort(persons,  new PersonComparer());

结果是就不输出了。

另外Sort()方法也可以把委托作为参数: 

 C# Code 
1
pulic  delegate  int Comparison<T>(T x, T y);
对于Person对象数组,参数T是Person类型:

 C# Code 
1
2
3
4
Array.Sort(persons,  delegate(Person p1, Person p2)
{
     return p1.Name.CompareTo(p2.Name);
});
或者可以使用λ表达式传送两个Person对象,给数组排序:

 C# Code 
1
Array.Sort(persons, (p1, p2) => p1.Name.CompareTo(p2.Name));
结果同样就不输出了。


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值