Let\'s assume that I have two classes:
class person
{
int ID
string name
Address address
}
class address
{
int ID
string street
string co
Try this one
public static IQueryable SortIQueryable(IQueryable data, string fieldName, string sortOrder)
{
if (string.IsNullOrWhiteSpace(fieldName)) return data;
if (string.IsNullOrWhiteSpace(sortOrder)) return data;
var param = Expression.Parameter(typeof(T), "i");
MemberExpression property = null;
string[] fieldNames = fieldName.Split('.');
foreach (string filed in fieldNames)
{
if (property == null)
{
property = Expression.Property(param, filed);
}
else
{
property = Expression.Property(property, filed);
}
}
Expression conversion = Expression.Convert(property, typeof(object));//Expression.Property(param, fieldName)
var mySortExpression = Expression.Lambda>(conversion, param);
return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
: data.OrderBy(mySortExpression);
}