Asp.net 在LINQ中按字符串值对IQueryable日期列排序
我试图通过字符串输入按特定列对Asp.net 在LINQ中按字符串值对IQueryable日期列排序,asp.net,linq,asp.net-mvc-3,Asp.net,Linq,Asp.net Mvc 3,我试图通过字符串输入按特定列对IQueryable对象进行排序 在IQueryable上调用.ToList()并通过列表列进行排序非常有效,但是在对日期列进行排序时,它会按字母顺序排序,这并不理想 如果有人能给我指出正确的方向,我将不胜感激 我的用法 IQueryable list=(从db.MyTable中的t1开始) 选择t1); 列表项已删除;//在这里分类 如果(!String.IsNullOrEmpty(OrderBy)) { itemsorted=list.OrderBy(Order
IQueryable
对象进行排序
在IQueryable
上调用.ToList()
并通过列表列进行排序非常有效,但是在对日期列进行排序时,它会按字母顺序排序,这并不理想
如果有人能给我指出正确的方向,我将不胜感激
我的用法
IQueryable list=(从db.MyTable中的t1开始)
选择t1);
列表项已删除;//在这里分类
如果(!String.IsNullOrEmpty(OrderBy))
{
itemsorted=list.OrderBy(OrderBy.ToList();
}
其他的
{
itemsorted=list.ToList();
}
扩展方法
使用System.Linq;
使用System.Collections.Generic;
使用制度;
使用System.Linq.Expressions;
运用系统反思;
公共静态类OrderByHelper
{
公共静态IEnumerable OrderBy(此IEnumerable可枚举,字符串OrderBy)
{
返回可枚举的.AsQueryable().OrderBy(OrderBy).AsEnumerable();
}
公共静态IQueryable OrderBy(此IQueryable集合,字符串OrderBy)
{
foreach(OrderByInfo-OrderByInfo-in-ParseOrderBy(orderBy))
collection=ApplyOrderBy(collection,orderByInfo);
回收;
}
专用静态IQueryable ApplyOrderBy(IQueryable集合、OrderByInfo OrderByInfo)
{
string[]props=orderByInfo.PropertyName.Split('.');
类型=类型(T);
ParameterExpression arg=Expression.Parameter(类型为“x”);
表达式expr=arg;
foreach(道具中的字符串道具)
{
//使用反射(非组件模型)镜像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);
string methodName=string.Empty;
如果(!orderByInfo.Initial&&collection是IOrderedQueryable)
{
if(orderByInfo.Direction==SortDirection.Ascending)
methodName=“ThenBy”;
其他的
methodName=“ThenByDescending”;
}
其他的
{
if(orderByInfo.Direction==SortDirection.Ascending)
methodName=“OrderBy”;
其他的
methodName=“OrderByDescending”;
}
//TODO:是否将缓存应用于通用方法?
return(IOrderedQueryable)typeof(Queryable).GetMethods().Single(
method=>method.Name==methodName
&&方法.IsGenericMethodDefinition
&&方法。GetGenericArguments()。长度==2
&&方法。GetParameters().Length==2)
.MakeGenericMethod(typeof(T),type)
.Invoke(null,新对象[]{collection,lambda});
}
私有静态IEnumerable ParseOrderBy(字符串orderBy)
{
if(String.IsNullOrEmpty(orderBy))
屈服断裂;
string[]items=orderBy.Split(',');
bool initial=true;
foreach(项中的字符串项)
{
字符串[]对=item.Trim().Split(“”);
如果(配对长度>2)
抛出新的ArgumentException(String.Format(“无效的OrderBy字符串“{0}”。按格式排序:Property,Property2 ASC,Property2 DESC”,item));
字符串属性=对[0]。修剪();
if(String.IsNullOrEmpty(prop))
抛出新ArgumentException(“无效属性。按格式排序:Property,Property2 ASC,Property2 DESC”);
SortDirection dir=SortDirection.升序;
如果(pair.Length==2)
dir=(“desc”.Equals(对[1].Trim(),StringComparison.OrdinalIgnoreCase)?SortDirection.Descending:SortDirection.Suscending);
返回新的OrderByInfo(){PropertyName=prop,Direction=dir,Initial=Initial};
初始值=假;
}
}
私有类OrderByInfo
{
公共字符串PropertyName{get;set;}
公共排序方向{get;set;}
公共布尔初始值{get;set;}
}
私有枚举排序定向
{
升序=0,
递减=1
}
公共静态IQueryable OrderByIQueryableStringValue(此IQueryable源,字符串排序,参数对象[]值)
{
var类型=类型(T);
var property=type.GetProperty(排序);
var参数=表达式参数(类型为“p”);
var propertyAccess=Expression.MakeMemberAccess(参数,属性);
var orderByExp=Expression.Lambda(propertyAccess,参数);
MethodCallExpression resultExp=Expression.Call(typeof(Queryable),“OrderBy”,新类型[]{Type,property.PropertyType},source.Expression,Expression.Quote(orderByExp));
返回source.Provider.CreateQuery(resultExp);
}
}
如果需要,已经有一个动态linq库,它有一个order by extension方法(和其他linq方法),它接受所有数据类型的字符串输入。请参见是否尝试调试此代码?
IQueryable<MyItemType> list = (from t1 in db.MyTable
select t1);
List<MyItemType> itemsSorted; // Sort here
if (!String.IsNullOrEmpty(OrderBy))
{
itemsSorted = list.OrderBy(OrderBy).ToList();
}
else
{
itemsSorted = list.ToList();
}
using System.Linq;
using System.Collections.Generic;
using System;
using System.Linq.Expressions;
using System.Reflection;
public static class OrderByHelper
{
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string orderBy)
{
return enumerable.AsQueryable().OrderBy(orderBy).AsEnumerable();
}
public static IQueryable<T> OrderBy<T>(this IQueryable<T> collection, string orderBy)
{
foreach (OrderByInfo orderByInfo in ParseOrderBy(orderBy))
collection = ApplyOrderBy<T>(collection, orderByInfo);
return collection;
}
private static IQueryable<T> ApplyOrderBy<T>(IQueryable<T> collection, OrderByInfo orderByInfo)
{
string[] props = orderByInfo.PropertyName.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);
string methodName = String.Empty;
if (!orderByInfo.Initial && collection is IOrderedQueryable<T>)
{
if (orderByInfo.Direction == SortDirection.Ascending)
methodName = "ThenBy";
else
methodName = "ThenByDescending";
}
else
{
if (orderByInfo.Direction == SortDirection.Ascending)
methodName = "OrderBy";
else
methodName = "OrderByDescending";
}
//TODO: apply caching to the generic methodsinfos?
return (IOrderedQueryable<T>)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[] { collection, lambda });
}
private static IEnumerable<OrderByInfo> ParseOrderBy(string orderBy)
{
if (String.IsNullOrEmpty(orderBy))
yield break;
string[] items = orderBy.Split(',');
bool initial = true;
foreach (string item in items)
{
string[] pair = item.Trim().Split(' ');
if (pair.Length > 2)
throw new ArgumentException(String.Format("Invalid OrderBy string '{0}'. Order By Format: Property, Property2 ASC, Property2 DESC", item));
string prop = pair[0].Trim();
if (String.IsNullOrEmpty(prop))
throw new ArgumentException("Invalid Property. Order By Format: Property, Property2 ASC, Property2 DESC");
SortDirection dir = SortDirection.Ascending;
if (pair.Length == 2)
dir = ("desc".Equals(pair[1].Trim(), StringComparison.OrdinalIgnoreCase) ? SortDirection.Descending : SortDirection.Ascending);
yield return new OrderByInfo() { PropertyName = prop, Direction = dir, Initial = initial };
initial = false;
}
}
private class OrderByInfo
{
public string PropertyName { get; set; }
public SortDirection Direction { get; set; }
public bool Initial { get; set; }
}
private enum SortDirection
{
Ascending = 0,
Descending = 1
}
public static IQueryable<T> OrderByIQueryableStringValue<T>(this IQueryable<T> source, string ordering, params object[] values)
{
var type = typeof(T);
var property = type.GetProperty(ordering);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
return source.Provider.CreateQuery<T>(resultExp);
}
}