C#如何對List中的Object進行排序

首先定義一個List類,這個類裏面包含了Name和Total兩個屬性變量,下面就是針對這兩個變量進行排序。spa

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條數據。code

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進行降序排序blog

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進行排序get

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);
相關文章
相關標籤/搜索