這個例子定義了一個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()方法可以得到對象執行個體的屬性/欄位值