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() 方法来进行排序
1:通过Total变量来进行升序排序
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);