Skip to content

Instantly share code, notes, and snippets.

@mshwf
Last active April 29, 2018 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshwf/97df90d19bd1210e76c16e3c6d1ffebf to your computer and use it in GitHub Desktop.
Save mshwf/97df90d19bd1210e76c16e3c6d1ffebf to your computer and use it in GitHub Desktop.
OrderBy by property name
public static class NiceLinq
{
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> notOrderedList, string propertyName)
{
var lambda = GetLambda<T>(propertyName);
var orderedList = notOrderedList.OrderBy(lambda);
return orderedList;
}
private static Func<T, object> GetLambda<T>(string propertyName)
{
var param = Expression.Parameter(typeof(T), "p");
var member = Expression.Property(param, propertyName);
Expression conversion = Expression.Convert(member, typeof(object)); //explicit casting is a must
var lambda = Expression.Lambda<Func<T, object>>(conversion, param);
return lambda.Compile();
}
}
public class Program
{
public static void Main(String[] args)
{
//some code from data storage source
var orderedStudents = allStudents.OrderBy("Name");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment