Last active
April 29, 2018 09:20
-
-
Save mshwf/97df90d19bd1210e76c16e3c6d1ffebf to your computer and use it in GitHub Desktop.
OrderBy by property name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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