linq 扩展,在查询中使用字符串表达式对结果进行排序
2011-04-14 19:04
411 查看
支持 info.A.B.C 这样的排序表达式
/// <summary> /// 在 linq 查询中使用字符串表达式进行排序 /// </summary> public static class OrderByStringExpressionExtensions { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { source, lambda }); return (IOrderedQueryable<T>)result; } }
相关文章推荐
- [深入学习C#]LINQ查询表达式详解(1)——基本语法、使用扩展方法和Lambda表达式简化LINQ查询
- 不使用遍历循环、Linq与Lamba表达式快速对List集合进行筛选与排序——在集合类里使用Find、FindAll与Sort
- SQL Server使用脚本对查询结果进行排序
- 使用 Order By字句对查询结果进行排序
- 转自:http://m.blog.csdn.net/article/details?id=6554168 在使用order by语句进行查询结果排序时,不同的数据库对于被排序字段数据行为null的情况
- linq to sql 查询后排序(字符串类型的数字进行排序)
- [代码]使用LINQ的查询结果填充XML树(LINQ to XML)
- lucene利用sort对查询结果进行排序示例
- 数据库查询排序使用随机排序结果示例(Oracle/MySQL/MS SQL Server)
- 深入理解 c# 第一章 使用lambda表达式 对 List <Product> 进行排序
- MySQL学习笔记——对查询结果进行排序
- C#中使用委托对字符串进行冒泡排序案例
- mysql查询按照指定字符串进行排序
- 数据库查询性能优化(合理使用索引|避免或简化排序|避免对大型表进行全表顺序扫描|避免使用相关的子查询|避免使用通配符匹配 )
- 《C#本质论》读书笔记(15)使用查询表达式的LINQ
- java 使用TreeSet将字符串中的数值进行排序
- 4种使用javascript正则表达式进行字符串replace操作的方法
- 使用Linq查询数据进行分页时遇到的性能问题
- C#使用LINQ查询表达式的基本子句总结
- 装饰者模式的学习(c#) EF SaveChanges() 报错(转载) C# 四舍五入 保留两位小数(转载) DataGridView样式生成器使用说明 MSSQL如何将查询结果拼接成字符串 快递查询 C# 通过smtp直接发送邮件 C# 带参访问接口,WebClient方式 C# 发送手机短信 文件 日志 写入 与读取