Linq排序有很多方法,好多都是关于静态排序,而静态排序相对来说比较简单,也比较容易实现,我这里需要一个动态排序。就是按字符串形式传递需要排序的列名,和"asc","desc"。这需要我们动态构建lamdba表达式,下面来看写的一个扩展类,部分源码参考了网上,还有的AsQueryable() 这个方法是看了http://blog.csdn.net/fhzh520/article/details/6062447 这篇文章才知道的..以前总是IEnumerable强转IQueryable但有时候失败.
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Blogs.DAL { public static class QueryableExtensions { public static IEnumerableOrderByEx(this IEnumerablequeryable, string propertyName) { return QueryableHelper.OrderBy(queryable, propertyName, false); } public static IEnumerableOrderByEx(this IEnumerablequeryable, string propertyName, bool desc) { return QueryableHelper.OrderBy(queryable, propertyName, desc); } private static class QueryableHelper{ private static Dictionary用法cache = new Dictionary (); public static IEnumerableOrderBy(IEnumerablequeryable, string propertyName, bool desc) { dynamic keySelector = GetLambdaExpression(propertyName); IQueryablequery = queryable.AsQueryable(); return desc ? Queryable.OrderByDescending(query, keySelector) : Queryable.OrderBy(query, keySelector); } private static LambdaExpression GetLambdaExpression(string propertyName) { if (cache.ContainsKey(propertyName)) return cache[propertyName]; var param = Expression.Parameter(typeof(T)); var body = Expression.Property(param, propertyName); var keySelector = Expression.Lambda(body, param); cache[propertyName] = keySelector; return keySelector; } } } }
IEnumerablelist;
//省略获取list
//升序
list.OrderByEx("排序列");
//倒序
list.OrderByEx("排序列",true);