Skip to content Skip to sidebar Skip to footer

Passing An Icomparer Parameter To Custom Linq Orderby Extension Method

After a good dose of Googling and trying some things and not finding/getting the desired result I decided to post this question. I have a custom made OrderBy extension method and n

Solution 1:

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>>:

publicstaticFunc<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 IComparerAlphanumComparator like this:

if (sort.Column.Contains("Index"))
{
    varfunc = Helpers.ExtensionMethods.CreateSelectorExpression<Divergence>(sort.Column);

    if (sort.Direction == SortDirection.Ascending)
    {
        return divergences.OrderBy(func, newAlphanumComparator());
    }
    else
    {
        return divergences.OrderByDescending(func, newAlphanumComparator());
    }
}

This involved a little bit more work but solved the problem in a generic fashion the way I wanted it to be.

Post a Comment for "Passing An Icomparer Parameter To Custom Linq Orderby Extension Method"