當前項目要求能對錶格的所有列進行排序。而我對linq掌握程度使我僅僅能寫出下面這樣的代碼:
case SortFields.Price: if (rules == SortRules.ESC) { result = result.OrderBy(s => s.Price); } else { result = result.OrderByDescending(s => s.Price); } break; case SortFields.BuyDate: if (rules == SortRules.ESC) { result = result.OrderBy(s => s.BuyDate); } else { result = result.OrderByDescending(s => s.BuyDate); } break;
這讓我十分鬱悶,寫枚舉,寫switch,,雖然寫法很簡單,但用這樣的寫法對每個欄位進行排序的話,我將面臨嚴重的體力活。
我想到了ADO的SQL字串拼接,此時的排序要求變的很輕鬆。
那麼作為新生事物的linq,ADO能輕鬆做到的事,沒理由做不到。
順著這樣的思路,在Google上一番搜尋。
在下面的文章中看到了希望:
http://www.cnblogs.com/126/archive/2007/09/09/887723.html
借鑒文章中的代碼,幾番嘗試,終於有點眉目,傳個欄位名字串和類型進行排序。。。
最後在下面的文章中直接找到了現成的(Orz):
http://hi.baidu.com/snake1964/blog/item/0b68d42ac1d4c120d52af149.html
照著上文的代碼,簡化了一下
public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyStr) where TEntity : class { ParameterExpression param = Expression.Parameter(typeof(TEntity), "c"); PropertyInfo property = typeof(TEntity).GetProperty(propertyStr); Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property); LambdaExpression le = Expression.Lambda(propertyAccessExpression, param); Type type = typeof(TEntity); MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(le)); return source.Provider.CreateQuery<TEntity>(resultExp); }
反射+System.Linq.Expressions下的幾個函數動態產生lambda運算式。