当前位置:首页 > C#教程 > C#高级

C# Array类的Sort()方法

array类实现了数组中元素的冒泡排序。sort()方法要求数组中的元素实现icomparable接口。如system.int32

和system.string实现了icomparable接口,所以下面的数组可以使用array.sort()。

string[] names = { "lili""heicer""lucy" };
array.sort(names);
foreach (string in names) {
console.writeline(n);
}

输出排序后的数组:

 

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

person类

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对象数组排序了:

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类
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()方法的第二个变元。

array.sort(persons, new personcomparer());

 

结果是就不输出了。

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

pulic delegate int comparison<</span>t>(t x, t y);

 

对于person对象数组,参数t是person类型:

array.sort(persons, delegate(person p1, person p2) {
return p1.name.compareto(p2.name);});

 

或者可以使用λ表达式传送两个person对象,给数组排序:

array.sort(persons, (p1, p2) => p1.name.compareto(p2.name));

 

结果同样就不输出了。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!