今天要對List排序,上網查了很多方法都感覺比較麻煩,現在終於找到了兩種比較簡便的方式,在此寫出來,防止忘記!同時供大家參考!
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />namespace ListSort<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> List<Customer> listCustomer = new List<Customer>();<br /> listCustomer.Add(new Customer { name = "客戶1", id = 0 });<br /> listCustomer.Add(new Customer { name = "客戶2", id = 1 });<br /> listCustomer.Add(new Customer { name = "客戶3", id = 5 });<br /> listCustomer.Add(new Customer { name = "客戶4", id = 3 });<br /> listCustomer.Add(new Customer { name = "客戶5", id = 4 });<br /> listCustomer.Add(new Customer { name = "客戶6", id = 5 });<br /> ///升序<br /> List<Customer> listCustomer1 = listCustomer.OrderBy(s => s.id).ToList<Customer>();<br /> //降序<br /> List<Customer> listCustomer2 = listCustomer.OrderByDescending(s => s.id).ToList<Customer>();<br /> //Linq排序方式<br /> List<Customer> listCustomer3 = (from c in listCustomer<br /> orderby c.id descending //ascending<br /> select c).ToList<Customer>();<br /> Console.WriteLine("List.OrderBy方法升序排序");<br /> foreach (Customer customer in listCustomer1)<br /> {<br /> Console.WriteLine(customer.name);<br /> }<br /> Console.WriteLine("List.OrderByDescending方法降序排序");<br /> foreach (Customer customer in listCustomer2)<br /> {<br /> Console.WriteLine(customer.name);<br /> }<br /> Console.WriteLine("Linq方法降序排序");<br /> foreach (Customer customer in listCustomer3)<br /> {<br /> Console.WriteLine(customer.name);<br /> }<br /> Console.ReadKey();<br /> }<br /> }<br /> class Customer<br /> {<br /> public int id { get; set; }<br /> public string name { get; set; }<br /> }<br />}<br />
效果展示: