這篇文章決定對最近一個單機版Web程序用到的東西總結一下。javascript
動態Linq結合反射對某字段排序:html
namespace 動態Linq { class Program { static void Main(string[] args) { List<Person> ListP = new List<Person>(); ListP.Add(new Person(1, "劉備", 40)); ListP.Add(new Person(2, "關羽", 35)); ListP.Add(new Person(3, "張飛", 29)); Hashtable ht = new Hashtable(); ht.Add("SortName","Id"); ht.Add("SortOrder","desc"); List<Person> ListT = PageSortList<Person>(ListP, ht); foreach (Person p in ListT) { Console.WriteLine(p.Id); } Console.ReadKey(); } //分頁排序 public static List<T> PageSortList<T>(List<T> ListT, Hashtable ht) { string SortName = ht["SortName"].ToString(); string SortOrder = ht["SortOrder"].ToString(); if (!string.IsNullOrEmpty(SortName)) { if (SortOrder.ToLower() == "desc") { ListT = ListT.OrderByDescending(m => m.GetType().GetProperty(SortName).GetValue(m, null)).ToList(); } else { ListT = ListT.OrderBy(m => m.GetType().GetProperty(SortName).GetValue(m, null)).ToList(); } } return ListT; } } public class Person { public Person(int id, string name, int age) { Id = id; Name = name; Age = age; } public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }
輸出以下:java
惟一要注意的東西,剛開始寫的不正確,實際上排序始終都是對屬性的值排序。這種東西有沒有用呢?git
線上系統通常不多用,可是最近項目要求作一個離線版Web,離線操做,連線導入數據。Oracle轉Xml,若是不大量採用泛型與反射,估計得寫一年左右。設計模式
動態Linq使用Where框架
namespace 動態Linq { class Program { static void Main(string[] args) { List<Person> ListP = new List<Person>(); ListP.Add(new Person(1, "劉備", 40)); ListP.Add(new Person(2, "關羽", 35)); ListP.Add(new Person(3, "張飛", 29)); Hashtable ht = new Hashtable(); ht.Add("Name","關羽"); List<Person> ListT = PageSortList<Person>(ListP, ht); foreach (Person p in ListT) { Console.WriteLine(p.Id); } Console.ReadKey(); } //分頁排序 public static List<T> PageSortList<T>(List<T> ListT, Hashtable ht) { string Key = ht.Cast<DictionaryEntry>().FirstOrDefault().Key.ToString(); string Value = ht.Cast<DictionaryEntry>().FirstOrDefault().Value.ToString(); ListT = ListT.Where(m => m.GetType().GetProperty(Key).GetValue(m, null).ToString() == Value).ToList(); return ListT; } } public class Person { public Person(int id, string name, int age) { Id = id; Name = name; Age = age; } public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }
輸出以下:post