I had to approach this differently.
I was trying to create a generic OrderBy
to be used with MvcContrib Grid, but passing the IComparer
to that custom OrderBy
expression did not work as I imagined it would work.
So I created this helper that receives a string in dot notation like Element1.Standard.Chapter.Manual.Name
and then returns an Expression<Func<T, string>>
:
public static Func<T, string> CreateSelectorExpression<T>(string propertyName) where T : class
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
Expression aggregateExpression = propertyName.Split('.').
Aggregate(parameterExpression as Expression, Expression.Property) as MemberExpression;
LambdaExpression exp = Expression.Lambda(aggregateExpression, parameterExpression);
return (Func<T, string>)exp.Compile();
}
This expression typed to T (in this case Divergence
object type) can then be passed (see func.Invoke
) to the standard LINQ OrderBy
operator where I can also pass the custom IComparer
AlphanumComparator
like this:
if (sort.Column.Contains("Index"))
{
var func = Helpers.ExtensionMethods.CreateSelectorExpression<Divergence>(sort.Column);
if (sort.Direction == SortDirection.Ascending)
{
return divergences.OrderBy(func, new AlphanumComparator());
}
else
{
return divergences.OrderByDescending(func, new AlphanumComparator());
}
}
This involved a little bit more work but solved the problem in a generic fashion the way I wanted it to be.