Monday, May 26, 2014

LINQ ORDER BY EXPRESSION PARAM

var param = Expression.Parameter(typeof(PERSON));
                
Func<PERSON, Object> sortExpression = Expression.Lambda<Func<AuditLogs, Object>>(Expression.Convert(Expression.Property(param, sortColumn), typeof(Object)), param).Compile();

if (sort == "DESC")
  result = result.OrderByDescending(sortExpression).ToList();
       else
  result = result.OrderBy(sortExpression).ToList();


OTHERS METHOD


public Func<T, Object> GetExpression<T>(String sortby)
{
  var param = Expression.Parameter(typeof(T));
  var sortExpression = Expression.Lambda<Func<T, Object>>(Expression.Convert(Expression.Property(param, sortby), typeof(Object)), param);
  
  return sortExpression.Compile();

}

  result = result.OrderBy(GetExpression<PERSON>(sortColumn)).ToList();

No comments:

Post a Comment