在 C# (.net 3.5 以後) 中集合是能夠經過 OrderBy() 和 OrderByDescending()方法來進行排序的,
若是須要集合中的元素是對象,還能夠經過 Lambda表達式進行按屬性排序,如:
定義一個學生類:this
class student { public int id { get; set; } public string name { get; set; } public string hometown { get; set; } public student(int id, string name, string hometowm) { this.id = id; this.name = name; this.hometown = hometown; } }
按學生名字排序,若是同名的,則按學號升序排序:spa
List<student> list = new List<student>() { new student(101, "olivia", "shantou"), new student(102, "sarah","shanghai"), new student(103, "nani", "china"), new student(104, "tommy", "maoming"), new student(105, "tommy", "shandong"), };
listBox.ItemsSource = list.OrderBy(x => x.name); // just order by name
listBox2.ItemsSource = list.OrderBy(x => x.name).ThenByDescending(x => x.id); // order by name, and then order desc by id.net
}
由上可見,多個條件時使用的是 ThenBy() 以及 ThenByDescending() 方法code
結果:
只按 name 排序:對象
先按 name 排序,再按 id 逆序:blog