I used the following methods to construct Order By Expression. Original Source
It is really slick. The downside is it only works if Property is
I have, IMHO, a simpler solution:
public static IOrderedQueryable Sort(this IQueryable source, bool ascending , string sortingProperty)
{
if (ascending)
return source.OrderBy(item => item.GetReflectedPropertyValue(sortingProperty));
else
return source.OrderByDescending(item => item.GetReflectedPropertyValue(sortingProperty));
}
private static object GetReflectedPropertyValue(this object subject, string field)
{
return subject.GetType().GetProperty(field).GetValue(subject, null);
}
The usage is:
myQueryableCollection.Sort(ascending: true, "Name")
Of course, the PropertyExist()
helper is a great addition...