Created
January 20, 2016 19:28
-
-
Save vendettamit/d84277f3b6f039973bf4 to your computer and use it in GitHub Desktop.
Helper class to pass dynamic orderby parameter in LINQ.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///<summary> | |
/// Usage - | |
/// if (QueryHelper.PropertyExists<Club>(orderBy)) | |
/// { | |
/// query = query.OrderByProperty(orderBy); | |
/// - OR - | |
/// query = query.OrderByPropertyDescending(orderBy); | |
/// } | |
///</summary> | |
public static class QueryHelper | |
{ | |
private static readonly MethodInfo OrderByMethod = | |
typeof (Queryable).GetMethods().Single(method => | |
method.Name == "OrderBy" && method.GetParameters().Length == 2); | |
private static readonly MethodInfo OrderByDescendingMethod = | |
typeof (Queryable).GetMethods().Single(method => | |
method.Name == "OrderByDescending" && method.GetParameters().Length == 2); | |
public static bool PropertyExists<T>(string propertyName) | |
{ | |
return typeof(T).GetProperty(propertyName, BindingFlags.IgnoreCase | | |
BindingFlags.Public | BindingFlags.Instance) != null; | |
} | |
public static IQueryable<T> OrderByProperty<T>( | |
this IQueryable<T> source, string propertyName) | |
{ | |
if (typeof (T).GetProperty(propertyName, BindingFlags.IgnoreCase | | |
BindingFlags.Public | BindingFlags.Instance) == null) | |
{ | |
return null; | |
} | |
ParameterExpression paramterExpression = Expression.Parameter(typeof (T)); | |
Expression orderByProperty = Expression.Property(paramterExpression, propertyName); | |
LambdaExpression lambda = Expression.Lambda(orderByProperty, paramterExpression); | |
MethodInfo genericMethod = | |
OrderByMethod.MakeGenericMethod(typeof (T), orderByProperty.Type); | |
object ret = genericMethod.Invoke(null, new object[] {source, lambda}); | |
return (IQueryable<T>) ret; | |
} | |
public static IQueryable<T> OrderByPropertyDescending<T>( | |
this IQueryable<T> source, string propertyName) | |
{ | |
if (typeof (T).GetProperty(propertyName, BindingFlags.IgnoreCase | | |
BindingFlags.Public | BindingFlags.Instance) == null) | |
{ | |
return null; | |
} | |
ParameterExpression paramterExpression = Expression.Parameter(typeof (T)); | |
Expression orderByProperty = Expression.Property(paramterExpression, propertyName); | |
LambdaExpression lambda = Expression.Lambda(orderByProperty, paramterExpression); | |
MethodInfo genericMethod = | |
OrderByDescendingMethod.MakeGenericMethod(typeof (T), orderByProperty.Type); | |
object ret = genericMethod.Invoke(null, new object[] {source, lambda}); | |
return (IQueryable<T>) ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment