您的位置:首页 > 其它

Linq初体验——Order By 通过属性名动态排序

2010-12-13 21:06 411 查看
当前项目要求能对表格的所有列进行排序。而我对linq掌握程度使我仅仅能写出下面这样的代码:

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表达式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: