Let me start by asking, please don't answer "use AsEnumerable or ToList before", this would get the data into memory and then order. Since I intend to use the same code to apply filter dynamically, that would not be helpfull.
Having this class:
public class Employee {
public string Name;
public IEnumerable<string> Childs;
}
I need to be able to sort an IQueryable by Childs property. Since I can't use string.Join directly, I was trying to make it dynamically using Expressions and combine it with a Stored Procedure that would return the names separeted by ",".
The problem is that I wasn't able to merge the procedure call inside the order expression. The order expression that I'm using was taken from this: Dynamic LINQ OrderBy on IEnumerable<T>
public static IOrderedQueryable<T> ApplyOrder<T>(this IQueryable<T> source, string propertyName, string methodName)
{
string[] properties = propertyName.Split('.');
Type type = typeof(T);
ParameterExpression parameter = Expression.Parameter(type);
Expression expression = parameter;
PropertyInfo propertyInfo = null;
foreach (string property in properties)
{
propertyInfo = type.GetProperty(property, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
{
/*
The ideia was to call the procedure here and use it's value to order the source query
*/
}
else
{
expression = Expression.Property(expression, propertyInfo);
type = propertyInfo.PropertyType;
}
}
Type orderDelegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression orderLambda = Expression.Lambda(orderDelegateType, expression, parameter);
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[] { source, orderLambda });
}
Honestly I'm studying Expression for a week now and still have no idea where to begin with.