C\#linq 조회 동적 OrderBy
7607 단어 Derby
sortOrder 는 정렬 형식,desc 또는 asc 입 니 다.
sortName 은 정렬 속성 이름 입 니 다.
1.반사 사용.
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
var resultList = sortOrder == "desc" ? groupList.OrderByDescending(p => GetPropertyValue(p, sortName)) : groupList.OrderBy(p => GetPropertyValue(p, sortName));
//linq :
//
var resultList1 = from p in groupList orderby GetPropertyValue(p, m.SortName) select p;
if (sortOrder == "desc")
resultList1 = from p in groupList orderby GetPropertyValue(p, sortName) descending select p;
2.AsQueryable()호출
범용 System.collections.Generic.IEnumerable
var groupQueryList = groupList.AsQueryable();//here
var tmpList = groupQueryList.OrderBy(sortName, sortOrder);
다음 확장 방법 이 필요 합 니 다:
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;
}
참고:http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet#41262