ArrayList 排序Sort()方法擴展


1、sort()

sort可以直接對默認繼承 IComparable接口的類進行排序,如:int、string....

ArrayList arrayList = new ArrayList();
int[] arr = new int[] { 1, 9, 3, 6, 5, 4, 7, 8,2};
arrayList.AddRange(arr);
arrayList.Sort();
//結果輸出結果:123456789

2、Sort()對自定義類進行排序

對自定義進行排序,該類必須實現IComparable或者使用“比較器”。

實現接口

    class Person : IComparable    
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public int CompareTo(object obj)
        {
            Person p = obj as Person;
            if (p == null)
            {
                throw new ArgumentException();
            }
            else
            {
                return  this.Age-p.Age;
            }
        }
    }
//這樣就可以 p.Sort()排序了,與int、string一樣了

比較器 比較器需實現IComparer接口

    class PersonSortByAgeAsc : IComparer
    {

        #region IComparer 成員

        public int Compare(object x, object y)
        {
            Person p1 = x as Person;
            Person p2 = y as Person;
            if (p1 != null && p2 != null)
            {
                return p1.Age - p2.Age;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        #endregion
    }
//使用比較器
arr.Sort(new PersonSortByAgeAsc());

下面是全部代碼,注釋的比較亂

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace _03集合
{
    class Program
    {
        static void Main(string[] args)
        {
            #region ArrayList集合,類似於一個object數組

            ArrayList arrayList = new ArrayList();

           // ////增加元素
           // //arrayList.Add(1);
           // //arrayList.Add(99.9);
           // //arrayList.Add("hello");
           // //Person p = new Person();
           // //p.Name = "張三";
           // //arrayList.Add(p);
           // //arrayList.Add(false);

           // ////在指定索引處插入一個新元素
           // arrayList.Insert(0, "============");

           // int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
           // string[] names = new string[] { "喬丹", "科比", "韋德" };
           //arrayList.AddRange(arr);
           // arrayList.AddRange(names);
           // //ArrayList arrList2 = new ArrayList();
           // //arrList2.Add("中國");
           // //arrList2.Add("美國");
           // //arrList2.Add("韓國");

           // ////通過調用AddRange()把另一個數組或者集合加到當前arrayList中。
           // //arrayList.AddRange(arrList2);

           // ////清空集合
           // //arrayList.Clear();


           // //Console.WriteLine("循環遍歷集合中每一個元素的內容:");

           // ////循環遍歷元素
           // ////ArrayList可以通過下標來訪問,原因就是ArrayList中有一個索引器
           // for (int i = 0; i < arrayList.Count; i++)
           // {
           //     Console.WriteLine(arrayList[i].ToString());
           // }






            ////默認創建好一個空的ArrayList后,Count是0.
            ////Count表示,集合中實際元素的個數。
            ////Capacity表示容量。
            //Console.WriteLine(arrayList.Count + "============" + arrayList.Capacity);
            //Console.ReadKey();


            //string[] n = new string[] { "a", "b", "c" };

            //Array.Clear(n, 0, n.Length);

            //Console.WriteLine(n.Length);
            //for (int i = 0; i < n.Length; i++)
            //{
            //    Console.WriteLine(n[i]+"★");
            //}
            //Console.ReadKey();


            //RemoveAt
            //集合初始化器
            //ArrayList arrList = new ArrayList() { 1, 2, 3, 4, 5, 6, "aaa", false, 99.9 };


            //arrList.RemoveAt(0);
            //arrList.RemoveAt(1);
            //arrList.RemoveAt(2);

            //for (int i = 0; i < arrList.Count; i++)
            //{
            //    Console.WriteLine(arrList[i]);
            //}



            ////要想清空集合,不能這么刪除,因為集合的Count是可以動態改變大小的。
            //for (int i = 0; i < arrList.Count; i++)
            //{
            //    arrList.RemoveAt(i);
            //}







            //ArrayList arrList = new ArrayList() { 1, 2, 3, 4, 5, 6, "aaa", false, 99.9, new Person() { Name = "張三" } };



            ////把一個集合轉換成一個數組
            //object[] objs = arrList.ToArray();


            ////根據元素內容來刪除,內部是通過調用元素Equals()方法來實現的比較,所以只要Equals()方法返回值為true,則認為這兩個值相等,值相等的,就可以被刪除。
            //arrList.Remove(1);
            //arrList.Remove(2);
            //arrList.Remove(3);
            //string a = new string(new char[] { 'a', 'a', 'a' });
            //Person p1 = new Person() { Name = "張三" };

            //arrList.Remove(a);
            //arrList.Remove(p1);//這個元素沒有刪除??


            //////Contains()方法內部判斷兩個值是否相等,也是通過Equals()方法來判斷的。
            ////if (arrList.Contains(1))
            ////{

            ////}

            //for (int i = 0; i < arrList.Count; i++)
            //{
            //    Console.WriteLine(arrList[i]);
            //}

            ////Console.WriteLine(arrList.Count);//?????
            //Console.ReadKey();




            #endregion

            //string
            #region ArrayList的Sort排序方法

            ////ArrayList arr = new ArrayList() { 0, 8, 32, 3, 4, 2, 432, 5, 234, 54323, 875, 45 };
            ////ArrayList arr = new ArrayList() { "Alice", "Wayen", "Chris", "Jerry", "Tom", "John", "Bob", "James", "Steve" };

            //ArrayList arr = new ArrayList() {
            //new Person(){ Name="Alice Wang", Age=19},
            //new Person(){ Name="Wayen Li", Age=12},
            //new Person(){ Name="Chris Sun", Age=21},
            //new Person(){ Name="Jerry Huang", Age=22}
            //};

            //Console.WriteLine("排序之前:");
            //for (int i = 0; i < arr.Count; i++)
            //{
            //    Console.WriteLine(((Person)arr[i]).Name);
            //}
            ////IComparable
            ////升序排序
            //arr.Sort();

            ////反轉
            ////arr.Reverse();

            //Console.WriteLine("排序之后:");
            //for (int i = 0; i < arr.Count; i++)
            //{
            //    Console.WriteLine(((Person)arr[i]).Name);
            //}
            //Console.ReadKey();

            #endregion



            #region 通過編寫不同的比較器,實現ArrayList的Sort()方法的不同方式排序

            ArrayList arr = new ArrayList() {
            new Person(){ Name="Alice Wang", Age=19},
            new Person(){ Name="Wayen Li", Age=12},
            new Person(){ Name="Chris Sun", Age=21},
            new Person(){ Name="Jerry Huang", Age=22}
            };
            arr.Sort();

            //按照年齡升序排序
            arr.Sort(new PersonSortByAgeAsc());


            //按照年齡降序排序
            //arr.Sort(new PersonSortByAgeDesc());


            //按照姓名的長度升序排序
            //arr.Sort(new PersonSortByNameLengthAsc());


            //按照姓名長度降序排序
            //arr.Sort(new PersonSortByNameLengthDesc());
            for (int i = 0; i < arr.Count; i++)
            {
                Console.WriteLine(((Person)arr[i]).Name.ToString()+","+((Person)arr[i]).Age.ToString());
            }
            Console.ReadKey();


            #endregion
        }
    }

    /// <summary>
    /// 這個類就是一個比較器,這個比較器是一個按年齡進行升序排序的比較器
    /// </summary>
    class PersonSortByAgeAsc : IComparer
    {

        #region IComparer 成員

        public int Compare(object x, object y)
        {
            Person p1 = x as Person;
            Person p2 = y as Person;
            if (p1 != null && p2 != null)
            {
                return p1.Age - p2.Age;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        #endregion
    }

    /// <summary>
    /// 按照年齡降序排序的比較器
    /// </summary>
    class PersonSortByAgeDesc : IComparer
    {

        #region IComparer 成員

        public int Compare(object x, object y)
        {
            Person p1 = x as Person;
            Person p2 = y as Person;
            if (p1 != null && p2 != null)
            {
                return p2.Age - p1.Age;
            }
            else
            {
                throw new ArgumentException();
            }
        }

        #endregion
    }
    //
    class Person : IComparable    
    {
        public string Name { get; set; }

        public int Age { get; set; }

        public int CompareTo(object obj)
        {
            Person p = obj as Person;
            if (p == null)
            {
                throw new ArgumentException();
            }
            else
            {
                return  this.Age-p.Age;
            }
        }
    }
}
View Code

 注:使用時,如非必要強烈建議使用list而不是arraylist 程序內省去了類型轉換過程,效率高


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM