一般我們在撰寫程式時,很常會使用到List<>來裝取自定義的類別陣列,跟一般的陣列插在哪呢?!好處是什麼?!好處就是一般的陣列需要先 宣告長度,而List<>不用,所以在資料個數不一的時候我們可能比較會使用List<>來裝載資料,並且依序地呈現給使用者 看,所以List<>的排序就變得將當重要了!
本篇文章將引導您將List<object>排序。
以身高為範例,首先我們先自定義一個類別用來放在List<>中用的。
1: public class TallItem{
2: public string name { set; get; }
3: public int Height { set; get; }
4: }
再來將個別的身高資料放入List<>中
1: public void InitialTallItem() {
2: List<TallItem> list_tallItems = new List<TallItem>();
3: list_tallItems.Add(new TallItem() { name = "Tony", Height = 180 });
4: list_tallItems.Add(new TallItem() { name = "Jorden", Height = 200 });
5: list_tallItems.Add(new TallItem() { name = "Nono", Height = 155 });
6: list_tallItems.Add(new TallItem() { name = "Jessica", Height = 166 });
7: }
再來是排序
1: list_tallItems.Sort((x, y) => { return -x.Height.CompareTo(y.Height); });
所以全部大概長這樣:
1: public void InitialTallItem() {
2: List<TallItem> list_tallItems = new List<TallItem>();
3: list_tallItems.Add(new TallItem() { name = "Tony", Height = 180 });
4: list_tallItems.Add(new TallItem() { name = "Jorden", Height = 200 });
5: list_tallItems.Add(new TallItem() { name = "Nono", Height = 155 });
6: list_tallItems.Add(new TallItem() { name = "Jessica", Height = 166 });
7:
8: list_tallItems.Sort((x, y) => { return -x.Height.CompareTo(y.Height); });
9:
10: for (int i = 0; i < list_tallItems.Count; i++) {
11: Debug.WriteLine(list_tallItems[i].name + ":" + list_tallItems[i].Height);
12: }
13: }
顯示的結果會是這樣:
1: Jorden:200
2: Tony:180
3: Jessica:166
4: Nono:155
如此一來List<TallItem>就經過排序囉,並且是由高到低排序。
除此之外也可以使用Linq語法來排序,此方法有點像在下SQL資料庫的語法,也比較淺顯易懂
1: List<TallItem> list_tallItems = new List<TallItem>();
2: list_tallItems.Add(new TallItem() { name = "Tony", Height = 180 });
3: list_tallItems.Add(new TallItem() { name = "Jorden", Height = 200 });
4: list_tallItems.Add(new TallItem() { name = "Nono", Height = 155 });
5: list_tallItems.Add(new TallItem() { name = "Jessica", Height = 166 });
6:
7: //依 身高 做遞增排序
8: list_tallItems = list_tallItems.OrderBy(x => x.Height).ToList();
9: foreach (TallItem item in list_tallItems)
10: {
11: Debug.WriteLine(item.name + ":" + item.Height);
12: }
13: Debug.WriteLine("================================");
14: //依 身高 做遞減排序
15: list_tallItems = list_tallItems.OrderByDescending(x => x.Height).ToList();
16: foreach (TallItem item in list_tallItems)
17: {
18: Debug.WriteLine(item.name + ":" + item.Height);
19: }
結果會像這樣:
1: Nono:155
2: Jessica:166
3: Tony:180
4: Jorden:200
5: ================================
6: Jorden:200
7: Tony:180
8: Jessica:166
9: Nono:155