C# Array.sort

Array.sort 有3种方式:

  • 待排序对象实现了IComparable<T> 接口
class Person :IComparable<Person>{
        private String firstname;

        public String Firstname
        {
            get { return firstname; }
            set { firstname = value; }
        }

        private String lastname;

        public String Lastname
        {
            get { return lastname; }
            set { lastname = value; }
        }

        public Person(String f,String l)
        {
            this.firstname = f;
            this.lastname = l;
        }

        
        public int CompareTo(Person other)
        {
            int result = this.Firstname.CompareTo(other.Firstname);
            if (result.Equals(0))
            {
                result = this.Lastname.CompareTo(other.Lastname);
            }
            return result;
        }
    }


 

  • 待排序对象你无法修改,将排序交给委托 Comparison<T> 去做
class util { 
        public static int comp(Person p1,Person p2){
            return p1.Lastname.CompareTo(p2.Lastname);
        }
    }

Person p1 = new Person("san", "zhang");
            Person p2 = new Person("si", "li");
            Person p3 = new Person("wu", "wang");
            Person[] a = { p3,p1,p2};
Array.Sort<Person>(a, new Comparison<Person>(util.comp));

或者

Array.Sort<Person>(a, (Person x, Person y) => { 
                int r = x.Firstname.CompareTo(y.Firstname);
                if (r.Equals(0)) { 
                     r = x.Lastname.CompareTo(y.Lastname); 
                }
                return r;
            });


 

  • 待排序对象你无法修改,将排序交给实现了IComparer<T>接口的对象去做
class PersonComparer : IComparer<Person> {

        public int Compare(Person x, Person y)
        {
            int result = x.Lastname.CompareTo(y.Lastname);
            if (result.Equals(0))
            {
                result = x.Firstname.CompareTo(y.Firstname);
            }
            return result;
        }
    }

Person p1 = new Person("san", "zhang");
            Person p2 = new Person("si", "li");
            Person p3 = new Person("wu", "wang");
            Person[] a = { p3,p1,p2};
            Array.Sort<Person>(a,new PersonComparer());


 

你可能感兴趣的:(C# Array.sort)