日期:2014-05-20  浏览次数:21093 次

linq to entity如何能动态地构造orderby子句?
比如像这样一个方法(方法只能返回IEnumerable), 现在只能按一个属性来排序,要按多个的话参数就要写的很复杂,而且不能通用..
除了用Dynamic Query Library外还有什么好办法吗。

C# code


IEnumerable<TEntity> GetList<TEntity, TSortKey>(int count, Expression<Func<TEntity, TSortKey>> order, bool ascending);




------解决方案--------------------
个人思路:自己写比较子,用比较子的切换解决不同的Orderby需求。
------解决方案--------------------
可以的,orderby函数可以多次调用,没调用一次都会附加到原来的上面去。
------解决方案--------------------
C# code

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Name
{
public static class LinqSort
{
/// <summary>
/// Linq动态排序
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="source">要排序的数据源</param>
/// <param name="value">排序依据(加空格)排序方式</param>
/// <returns>IOrderedQueryable</returns>
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string value)
{
string[] arr = value.Split(' ');
string Name = arr[1].ToUpper() == "DESC" ? "OrderByDescending" : "OrderBy";
return ApplyOrder<T>(source, arr[0], Name);
}
/// <summary>
/// Linq动态排序再排序
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="source">要排序的数据源</param>
/// <param name="value">排序依据(加空格)排序方式</param>
/// <returns>IOrderedQueryable</returns>
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string value)
{
string[] arr = value.Split(' ');
string Name = arr[1].ToUpper() == "DESC" ? "ThenByDescending" : "ThenBy";
return ApplyOrder<T>(source, arr[0], Name);
}
static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
{
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "a");
PropertyInfo pi = type.GetProperty(property);
Expression expr = Expression.Property(arg, 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(
a => a.Name == methodName
&& a.IsGenericMethodDefinition
&& a.GetGenericArguments().Length == 2
&& a.GetParameters().Length == 2).MakeGenericMethod(typeof(T), type).Invoke(null, new object[] { source, lambda });
return (IOrderedQueryable<T>)result;
}
}
}

------解决方案--------------------
动态构建OrderBy的Lambda表达式
http://blog.csdn.net/Sandy945/archive/2010/07/14/5735326.aspx
------解决方案--------------------
from y in db.ViewCompanys order by y.filed1 ,y.fiel2 select y