I want to generate expression by string parameter,some code like:
private Expression> Generate(string orderby)
{
switch (orderb
public static IQueryable OrderByHelper(this IQueryable source, string propertyName, string sortDirection)
{
try
{
if (source == null)
{
return source;
}
if (propertyName == null)
{
return source;
}
propertyName = propertyName.First().ToString().ToUpper(new CultureInfo("en-US", false)) + propertyName.Substring(1);
var type = typeof(T);
var arg = Expression.Parameter(type, "x");
var propertyInfo = type.GetProperty(propertyName);
var mExpr = Expression.Property(arg, propertyInfo);
type = propertyInfo.PropertyType;
var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
var lambda = Expression.Lambda(delegateType, mExpr, arg);
var methodName = !string.IsNullOrEmpty(sortDirection) && sortDirection.ToLower(new CultureInfo("en-US", false)) == "desc" ? "OrderByDescending" : "OrderBy";
var orderedSource = 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 (IQueryable)orderedSource;
}
catch (Exception)
{
return source;
}
}