4.2 对象的排序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { List<Order> list = new List<Order>(); list.Add(new Order() { name = "a", age = 2 }); list.Add(new Order() { name = "b", age = 1 }); list.Add(new Order() { name = "b", age = 2 }); List<Order.Sorter> sorterList = new List<Order.Sorter>(); sorterList.Add(new Order.Sorter(Order.SortDirection.ASC,Order.SortField.Name)); sorterList.Add(new Order.Sorter(Order.SortDirection.DES, Order.SortField.Age)); list.Sort(Order.GetComparer(sorterList)); foreach (Order item in list) { Console.WriteLine("{0}:{1}", item.name, item.age); } Console.Read(); } } public class Order { public string name; public int age; public static OrderComparer GetComparer(List<Sorter> list) { return new OrderComparer(list); } public class OrderComparer : IComparer<Order> { private List<Sorter> list; public OrderComparer(List<Sorter> list) { this.list = list; } public int Compare(Order x, Order y, SortField field, SortDirection direct) { int result = 0; switch (field) { case SortField.Name: if (direct == SortDirection.ASC) result = x.name.CompareTo(y.name); else result = y.name.CompareTo(x.name); break; case SortField.Age: if (direct == SortDirection.ASC) result = x.age.CompareTo(y.age); else result = y.age.CompareTo(x.age); break; } return result; } public int Compare(Order x, Order y) { int result = 0; foreach (Sorter item in list) { result = Compare(x, y, item.field, item.direct); if (result != 0) break; } return result; } } public enum SortDirection { ASC = 0, DES } public enum SortField { Name = 0, Age } public struct Sorter { public SortDirection direct; public SortField field; public Sorter(SortDirection direct, SortField field) { this.direct = direct; this.field = field; } } } }