linq 动态排序
/// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="sortExpression"></param> /// <param name="sortDirection"></param> /// <returns></returns> public static IQueryable<T> DataSorting<T>(IQueryable<T> source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") sortingDir = "OrderBy"; else if (sortDirection.ToUpper().Trim() == "DESC") sortingDir = "OrderByDescending"; ParameterExpression param = Expression.Parameter(typeof(T), sortExpression); PropertyInfo pi = typeof(T).GetProperty(sortExpression); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param)); IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr); return query; }