C#如何對(duì)List中的Object進(jìn)行排序
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
首先定義一個(gè)List類(lèi),這個(gè)類(lèi)里面包含了Name和Total兩個(gè)屬性變量,下面就是針對(duì)這兩個(gè)變量進(jìn)行排序。
public class Player { public string Name { get; set; } public int Total { get; set; } public Player(string name, int total) { Name = name; Total = total; } } 而后咱們建立一個(gè)List,這個(gè)List是Player對(duì)象的一個(gè)List集,建立好List后,須要為L(zhǎng)ist添加一些節(jié)點(diǎn),下面添加了6條數(shù)據(jù)。
List<Player> lst = new List<player>(); lst.Add(new Player("John", 100)); lst.Add(new Player("Smith", 120)); lst.Add(new Player("Cait", 97)); lst.Add(new Player("Irene", 100)); lst.Add(new Player("Ben", 100)); lst.Add(new Player("Deniel", 88));
咱們經(jīng)過(guò)List.Sort() 方法來(lái)進(jìn)行排序 lst.Sort(delegate(Player x, Player y) { return x.Total.CompareTo(y.Total); }); 2:經(jīng)過(guò)Total進(jìn)行降序排序 lst.Sort(delegate(Player x, Player y) { return y.Total.CompareTo(x.Total); }); 3:經(jīng)過(guò)多個(gè)元素進(jìn)行排序 lst.Sort(delegate(Player x, Player y) { // Sort by total in descending order int a = y.Total.CompareTo(x.Total); // Both player has the same total. // Sort by name in ascending order if (a == 0) a = x.Name.CompareTo(y.Name); return a; }); 4:經(jīng)過(guò)Linq進(jìn)行排序 var result1 = lst.OrderBy(a => a.Total); var result3 = lst.OrderBy(a => a.Total).ThenBy(a => a.Name); var result2 = lst.OrderByDescending(a => a.Total).ThenByDescending(a => a.Name); 該文章在 2021/3/9 19:02:21 編輯過(guò) |
關(guān)鍵字查詢(xún)
相關(guān)文章
正在查詢(xún)... |