Skip to content

Instantly share code, notes, and snippets.

@Liminiens
Created June 29, 2018 12:59
Show Gist options
  • Save Liminiens/27183478d62675ec195c500e00c1888b to your computer and use it in GitHub Desktop.
Save Liminiens/27183478d62675ec195c500e00c1888b to your computer and use it in GitHub Desktop.
public static class UntypedOrderBy
{
private static readonly ConcurrentDictionary<(Type, string), Delegate> Lambdas = new ConcurrentDictionary<(Type, string), Delegate>();
public static IEnumerable<TType> OrderyByProperty<TType>(this IEnumerable<TType> collection, string name)
{
var lambda = Lambdas.GetOrAdd((typeof(TType), name), key =>
{
ParameterExpression entity = Expression.Parameter(typeof(TType));
MethodCallExpression getterCall =
Expression.Call(entity, typeof(TType).GetProperty(name).GetGetMethod());
UnaryExpression castToObject = Expression.Convert(getterCall, typeof(object));
return Expression.Lambda(castToObject, entity).Compile();
});
return collection.OrderBy((Func<TType, object>)lambda);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment