推薦:http://www.cnblogs.com/roucheng/p/dushubiji.html ...
class Pet { public string Name{get;set;} public int Age{get;set;} } void Main() { Pet[] pets = { new Pet { Name="Tim", Age=18 }, new Pet { Name="Allen", Age=22 }, new Pet { Name="Bill", Age=20 } }; //如果我們想根據Age進行排序 很容易想到這樣來寫: var query= from p in pets orderby p.Age select p; query.ToList().ForEach(q=>Console.WriteLine(q.Name +" "+q.Age)); /* 得到結果: Tim 18 Bill 20 Allen 22 */ } //但是有時項目內有多個排序條件 如有時要根據Name排序 有時要根據Age排序 何問起 hovertree.com //這時我們就要用到動態排序: void Main() { Pet[] pets = { new Pet { Name="Tim", Age=18 }, new Pet { Name="Allen", Age=22 }, new Pet { Name="Bill", Age=20 } }; Console.WriteLine("Before Orderby:/r/n"); pets.ToList().ForEach(p=>Console.WriteLine(p.Name +" "+p.Age)); var query= from p in pets orderby GetPropertyValue(p,"Age") select p; Console.WriteLine("/r/nAfter Orderby:/r/n"); query.ToList().ForEach(q=>Console.WriteLine(q.Name +" "+q.Age)); /* Before Orderby: Tim 18 Allen 22 Bill 20 After Orderby: Tim 18 Bill 20 Allen 22 */ } /* 何問起 hovertree.com */ private static object GetPropertyValue(object obj, string property) { System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property); return propertyInfo.GetValue(obj, null); }
推薦:http://www.cnblogs.com/roucheng/p/dushubiji.html