Untitled - MARKUP 0.81 KB
                                
                                    using System;
using System.Linq;
using System.Linq.Expressions;

// ...

public IQueryable<T> SortByNestedProperty<T>(IQueryable<T> query, string propertyName, string sortDirection)
{
    var parameter = Expression.Parameter(typeof(T), "x");
    var propertyAccess = propertyName.Split('.')
        .Aggregate((Expression)parameter, Expression.Property);
    var lambda = Expression.Lambda(propertyAccess, parameter);

    var orderByExpression = Expression.Call(
        typeof(Queryable),
        sortDirection == "desc" ? "OrderByDescending" : "OrderBy",
        new Type[] { typeof(T), propertyAccess.Type },
        query.Expression,
        lambda
    );

    return query.Provider.CreateQuery<T>(orderByExpression);
}
                                
                            

Paste Hosted With By Wklejamy.pl