数组中的对象排序--IComparable

l给数组中的对象排序
(实现IComparable的重要性 )
要使数组中的对象能够排序,其对象必须实现IComparable接口的CompareTo方法。可以使用Array类的Sort方法实现排序。

 

 数组的排序:

 Person[] persons = new Person[3];
        Person wm = new Person("郭", "明");
       Person wm1 = new Person("王", "明");
        persons[0] = wm;
        persons[1] = new Person("小", "万");
        persons[2] = new Person("刘", "心");
        Array.Sort(persons);
        foreach (Person  p in persons )
        {
           Response.Write(p.FirstName +p.LastName +"<br/>");
        }

类中:(利用接口)

public class Person:IComparable 
{

private string firstname;

    public string FirstName
    {
        get { return firstname; }
        set { firstname = value; }
    }
    private string lastname;

    public string LastName
    {
        get { return lastname; }
        set { lastname = value; }
    }

 

//IComparable 成员

  public int CompareTo(object obj)
   {
       Person p = obj as Person;
       if (p == null)
       {
           throw new ArgumentException("obj is not a person");
       }
       int first = this.firstname.CompareTo(p.firstname);
       if (first == 0)//如果firstname相同则比较lastname
       {
           first = this.lastname.CompareTo(p.lastname);
           return first;
       }
       else
           return first;
          }

}

按照数组中元素录入的先后顺序进行排序

你可能感兴趣的:(数组中的对象排序--IComparable)