linq扩展之动态排序

时间:2022-09-23 10:40:14

前两天看QQ群里面,一位朋友问的问题,说在linq中怎么实现动态排序呢,自己想了半天,没有头绪,网上找了下相关的资料,看了下,收益挺多,记录下来。

之前我们没有如果不知道动态排序的方法的话,我们可能会这样写

[code lang="csharp"]
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;
[/code]

这种代码,我们看起来极其繁琐,绝对是个体力活。。。
通过百度,我看到博客园的一篇文章,突然在黑夜中看到了光明
http://www.cnblogs.com/126/archive/2007/09/09/887723.html
根据这篇文章的讲解,我们可以看到:
Linq To Sql支持用户动态生成lambda表达式,作者通过自定义的方法,传一个实体对象过去,根据判断每个字段的值是否为null,来进行动态生成lambda表达式。
基本原理懂了,下面就剩写代码了。
由于老外已经有这方面的经验,已经写出现成的helper,我这边就不造车轮了。
直接贴老外的代码:
[code lang="csharp"]
/***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is LINQExtensions.StringFieldNameSortingSupport.
*
* The Initial Developer of the Original Code is
* Davy Landman.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace LINQExtensions
{
public static class StringFieldNameSortingSupport
{
#region Private expression tree helpers

private static LambdaExpression GenerateSelector<TEntity>(String propertyName, out Type resultType) where TEntity : class
{
// Create a parameter to pass into the Lambda expression (Entity => Entity.OrderByField).
var parameter = Expression.Parameter(typeof(TEntity), "Entity");
// create the selector part, but support child properties
PropertyInfo property;
Expression propertyAccess;
if (propertyName.Contains('.'))
{
// support to be sorted on child fields.
String[] childProperties = propertyName.Split('.');
property = typeof(TEntity).GetProperty(childProperties[0]);
propertyAccess = Expression.MakeMemberAccess(parameter, property);
for (int i = 1; i < childProperties.Length; i++)
{
property = property.PropertyType.GetProperty(childProperties[i]);
propertyAccess = Expression.MakeMemberAccess(propertyAccess, property);
}
}
else
{
property = typeof(TEntity).GetProperty(propertyName);
propertyAccess = Expression.MakeMemberAccess(parameter, property);
}
resultType = property.PropertyType;
// Create the order by expression.
return Expression.Lambda(propertyAccess, parameter);
}
private static MethodCallExpression GenerateMethodCall<TEntity>(IQueryable<TEntity> source, string methodName, String fieldName) where TEntity : class
{
Type type = typeof(TEntity);
Type selectorResultType;
LambdaExpression selector = GenerateSelector<TEntity>(fieldName, out selectorResultType);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
new Type[] { type, selectorResultType },
source.Expression, Expression.Quote(selector));
return resultExp;
}
#endregion
public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string fieldName) where TEntity : class
{
MethodCallExpression resultExp = GenerateMethodCall<TEntity>(source, "OrderBy", fieldName);
return source.Provider.CreateQuery<TEntity>(resultExp) as IOrderedQueryable<TEntity>;
}

public static IOrderedQueryable<TEntity> OrderByDescending<TEntity>(this IQueryable<TEntity> source, string fieldName) where TEntity : class
{
MethodCallExpression resultExp = GenerateMethodCall<TEntity>(source, "OrderByDescending", fieldName);
return source.Provider.CreateQuery<TEntity>(resultExp) as IOrderedQueryable<TEntity>;
}
public static IOrderedQueryable<TEntity> ThenBy<TEntity>(this IOrderedQueryable<TEntity> source, string fieldName) where TEntity : class
{
MethodCallExpression resultExp = GenerateMethodCall<TEntity>(source, "ThenBy", fieldName);
return source.Provider.CreateQuery<TEntity>(resultExp) as IOrderedQueryable<TEntity>;
}
public static IOrderedQueryable<TEntity> ThenByDescending<TEntity>(this IOrderedQueryable<TEntity> source, string fieldName) where TEntity : class
{
MethodCallExpression resultExp = GenerateMethodCall<TEntity>(source, "ThenByDescending", fieldName);
return source.Provider.CreateQuery<TEntity>(resultExp) as IOrderedQueryable<TEntity>;
}
public static IOrderedQueryable<TEntity> OrderUsingSortExpression<TEntity>(this IQueryable<TEntity> source, string sortExpression) where TEntity : class
{
String[] orderFields = sortExpression.Split(',');
IOrderedQueryable<TEntity> result = null;
for (int currentFieldIndex = 0; currentFieldIndex < orderFields.Length; currentFieldIndex++)
{
String[] expressionPart = orderFields[currentFieldIndex].Trim().Split(' ');
String sortField = expressionPart[0];
Boolean sortDescending = (expressionPart.Length == 2) && (expressionPart[1].Equals("DESC", StringComparison.OrdinalIgnoreCase));
if (sortDescending)
{
result = currentFieldIndex == 0 ? source.OrderByDescending(sortField) : result.ThenByDescending(sortField);
}
else
{
result = currentFieldIndex == 0 ? source.OrderBy(sortField) : result.ThenBy(sortField);
}
}
return result;
}
}
}
[/code]

使用方法:
查看代码中的:
OrderUsingSortExpression这个方法,这个方法就是使用方法,按照上面的传参就ok了

linq扩展之动态排序的更多相关文章

  1. LINQ中的动态排序

    使用Linq动态属性排序 使用反射: public static Func<T,Tkey> DynamicLambda<T, Tkey>(string propertyName ...

  2. 写一个针对IQueryable&lt&semi;T&gt&semi;的扩展方法支持动态排序

    所谓的动态排序是指支持任意字段.任意升序降序的排序.我们希望在客户端按如下格式写: localhost:8000/api/items?sort=titlelocalhost:8000/api/item ...

  3. linq字符串搜索条件&comma;排序条件-linq动态查询语句 Dynamic LINQ

    在做搜索和排序的时候,往往是前台传过来的字符串做条件,参数的数量还不定,这就需要用拼sql语句一样拼linq语句.而linq语句又是强类型的,不能用字符串拼出来. 现在好了,有个开源的linq扩展方法 ...

  4. 构建ASP&period;NET MVC4&plus;EF5&plus;EasyUI&plus;Unity2&period;x注入的后台管理系统(17)-LinQ动态排序

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(17)-LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为s ...

  5. LinQ动态排序

    LinQ动态排序 首先修复程序中的一个BUG这个BUG在GridPager类中,把sord修改为sort这个名称填写错误,会导致后台一直无法获取datagrid的排序字段 本来是没有这一讲的,为了使2 ...

  6. Linq to Sql &colon; 动态构造Expression进行动态查询

    原文:Linq to Sql : 动态构造Expression进行动态查询 前一篇在介绍动态查询时,提到一个问题:如何根据用户的输入条件,动态构造这个过滤条件表达式呢?Expression<Fu ...

  7. ABP框架源码中的Linq扩展方法

    文件目录:aspnetboilerplate-dev\aspnetboilerplate-dev\src\Abp\Collections\Extensions\EnumerableExtensions ...

  8. 通过orderby关键字,LINQ可以实现升序和降序排序。LINQ还支持次要排序。

    通过orderby关键字,LINQ可以实现升序和降序排序.LINQ还支持次要排序. LINQ默认的排序是升序排序,如果你想使用降序排序,就要使用descending关键字. static void M ...

  9. 在Asp &period;net core 中通过属性映射实现动态排序和数据塑形

    目录 属性映射服务实现 动态排序 数据塑形 属性映射服务实现 public class PropertyMappingValue { public IEnumerable<string> ...

随机推荐

  1. GO语言练习:反射

    列举几个反射的例子:1)简单类型反射,2)复杂类型反射,3)对反射回来的数据的可修改属性 1.简单类型反射 1.1)代码 package main import ( "fmt" & ...

  2. XmlHelper

    获取XML节点的值(http服务使用xml传输数据,节点名称唯一) /// <summary> /// 获取xml节点的值 /// </summary> /// <par ...

  3. 按要求编写Java应用程序。 (1)创建一个叫做机动车的类: 属性:车牌号&lpar;String&rpar;,车速&lpar;int&rpar;,载重量&lpar;double&rpar; 功能:加速&lpar;车速自增&rpar;、减速&lpar;车速自减&rpar;、修改车牌号,查询车的载重量。 编写两个构造方法:一个没有形参,在方法中将车牌号设置&OpenCurlyDoubleQuote;XX1234”,速 度设置为100,载重量设置为100;另一个能为对象的所有属性赋值; (2)创建主类: 在主类中创建两个机动车对象。 创建第

    package com.hanqi.test; public class jidongche { private String chepaihao;//车牌号 private int speed;// ...

  4. 我的ElasticSearch集群部署总结--大数据搜索引擎你不得不知

    摘要:世上有三类书籍:1.介绍知识,2.阐述理论,3.工具书:世间也存在两类知识:1.技术,2.思想.以下是我在部署ElasticSearch集群时的经验总结,它们大体属于第一类知识“techknow ...

  5. MYSQL--事务处理

    1.用begin,rollback,commit来实现 begin 开始一个事务 rollback 事务回滚 commit  事务确认 2.直接用set来改变mysql的自动提交模式 MYSQL默认是 ...

  6. EPEL库安装

    EPEL是yum的一个软件源,里面包含了许多基本源里没有的软件了,但在我们在使用epel时是需要安装它才可以了.EPEL,即Extra Packages for Enterprise Linux的简称 ...

  7. COM组件开发实践(七)---多线程ActiveX控件和自动调整ActiveX控件大小&lpar;上&rpar;

    声明:本文代码基于CodeProject的文章<A Complete ActiveX Web Control Tutorial>修改而来,因此同样遵循Code Project Open L ...

  8. C&num; 如何利用反射来加载程序集,并调用程序集中有关类的方法【转】

    假设在C盘根目录下有个Dog的Dll程序集文件,该程序集文件中包含类Dog 该类中有个狗叫几声的方法,如何通过反射来加载这个C:\Dog.dll,并且调用Dog类里面的Sound方法呢: public ...

  9. 【poj解题】1308

    判断一个图是否是一个树,树满足一下2个条件即可:1. 边树比node数少12. 所有node的入度非0即1 节点数是0的时候,空树,合法树~ 代码如下 #include <stdio.h> ...

  10. 谈谈自己体会到的HTML5

    # 谈谈自己体会到的HTML5 很多介绍HTML5的文章,都是从以下几个方面去介绍的:语义化.丰富的表单.本地存储.多媒体.地理位置等等.纸上得来终觉浅,现在有了一定的实践经验之后,本人对其有了更加深 ...