C#如何对List中的Object进行排序
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
首先定义一个List类,这个类里面包含了Name和Total两个属性变量,下面就是针对这两个变量进行排序。
public class Player { public string Name { get; set; } public int Total { get; set; } public Player(string name, int total) { Name = name; Total = total; } } 而后咱们建立一个List,这个List是Player对象的一个List集,建立好List后,须要为List添加一些节点,下面添加了6条数据。
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));
咱们经过List.Sort() 方法来进行排序 lst.Sort(delegate(Player x, Player y) { return x.Total.CompareTo(y.Total); }); 2:经过Total进行降序排序 lst.Sort(delegate(Player x, Player y) { return y.Total.CompareTo(x.Total); }); 3:经过多个元素进行排序 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:经过Linq进行排序 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 编辑过 |
关键字查询
相关文章
正在查询... |