Array类的Sort()方法

来源:互联网 发布:军事题材电视剧知乎 编辑:程序博客网 时间:2024/05/14 17:42

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
原创粉丝点击