close

List中可以呼叫Sort方法進行由小到大的排序:

List<int> amount = new List<int>();
amount.Add(10);
amount.Add(5);
amount.Add(8);
amount.Add(7);
amount.Add(2);

amount.Sort();
for(int i = 0;i<amount.Count;i++)
{
Debug.Log (amount[i]);
}

//Output--
2
5
7
8
10
//--------


如果想要值由大排到小,
比較簡單的方法則是將Sort後的List由後面往前面讀:

for(int i = amount.Count-1;i>=0 ;i--)
{
Debug.Log (amount[i]);
}
//Output--
10
8
7
5
2
//--------

也可以在Sort方法中將資料兩兩比較,
下面範例使用了Lambda的運算式,
並使用int.CompareTo的方法比較兩兩資料的大小,
當x > y時回傳1,
x = y 時回傳0,
x < y 時回傳-1,
因Sort排序為由小至大,
所以我們將比較完的值加個負號,
便可以獲得由大至小的排序

部分程式碼:
amount.Sort((x,y)=>{ return -x.CompareTo(y);} );
for(int i = 0;i<amount.Count;i++)
{
Debug.Log (amount[i]);
}

//Output--
10
8
7
5
2
//--------

arrow
arrow
    文章標籤
    List sort Unity
    全站熱搜

    WilsonYo 發表在 痞客邦 留言(0) 人氣()