linq to entity如何能动态地构造orderby子句?

种草德鲁伊 2011-07-01 11:46:23
比如像这样一个方法(方法只能返回IEnumerable), 现在只能按一个属性来排序,要按多个的话参数就要写的很复杂,而且不能通用..
除了用Dynamic Query Library外还有什么好办法吗。



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

...全文
231 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿非 2011-07-01
  • 打赏
  • 举报
回复
种草德鲁伊 2011-07-01
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 karascanvas 的回复:]

引用 4 楼 q107770540 的回复:

C# code



方法只能返回IEnumerable
[/Quote]

好吧,看错了...
种草德鲁伊 2011-07-01
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 q107770540 的回复:]

C# code

[/Quote]

方法只能返回IEnumerable
q107770540 2011-07-01
  • 打赏
  • 举报
回复

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;
}
}
}
种草德鲁伊 2011-07-01
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 kurehu 的回复:]

可以的,orderby函数可以多次调用,没调用一次都会附加到原来的上面去。

[/Quote]

确实可以,现在的问题是要把表达式作为参数传递,如果要传多个的话,就必须定义一大堆参数...
三多 2011-07-01
  • 打赏
  • 举报
回复
可以的,orderby函数可以多次调用,没调用一次都会附加到原来的上面去。
老毕 2011-07-01
  • 打赏
  • 举报
回复
个人思路:自己写比较子,用比较子的切换解决不同的Orderby需求。
xuexiaodong2009 2011-07-01
  • 打赏
  • 举报
回复
from y in db.ViewCompanys order by y.filed1 ,y.fiel2 select y

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧