Array.Sort()靜態方法對數組進行排序

來源:互聯網
上載者:User

這個例子定義了一個int數組,然後使用Array.Sort(arr)靜態方法對此數組進行排序,最後輸出排序後的數組。以上例子將毫無意外的依次輸出1,2,3,4,5,6.

 

int[] intArray = new int[]{2,3,6,1,4,5};
Array.Sort(intArray);
Array.ForEach<int>(intArray,(i)=>Console.WriteLine(i));


排序是編程中常用的法算之一,排序的方法有很多種,下面介紹一種簡單有效排序方法,代碼如下:

private bool isReverse = false;
private void Sort(PersonalNotificationEntity [] list,string key)
{
   if ( isReverse )
   {
     Array.Reverse(list);
     isReverse = false;
   }
   else
   {
       int len = list.Length;
      Type type = typeof(PersonalNotificationEntity);
      object [] keys = new object[len];
     for(int i = 0 ; i < len ; i++)
    {
         keys[i] = type.InvokeMember(key,BindingFlags.GetField ,null,list[i],null);
     }
     Array.Sort(keys,list);
    isReverse = true;
     }
}

這裡使用了Array.Sort()和Array.Reverse()方法對資料進行正/反排序,變數isReverse做為反排序的標誌位
方法傳入了2個參數,一個是要排序的對象數組list,一個是排序關鍵字key,即要對象的根據哪個屬性或欄位來進行排序(這個值是等於對象的屬性/欄位名)
type.InvokeMember()方法可以得到對象執行個體的屬性/欄位值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.