I'm creating a dynamic expression, which will order items in a list by some rule (lambda exp.). This is the code:
Expression<Func<String, String>> exp = o => o;
MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);
Now I want to execute previously created expression on specific data to sort it, but it fails because of some strange exceptions like "Lambda Parameter not in scope" or "Argument expression is not valid".
var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };
// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);
Can somebody help me with this?
order any enumerable by a property(no reflection):
public static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> items, string property, bool ascending)
{
var MyObject = Expression.Parameter(typeof (T), "MyObject");
var MyEnumeratedObject = Expression.Parameter(typeof (IEnumerable<T>), "MyEnumeratedObject");
var MyProperty = Expression.Property(MyObject, property);
var MyLamda = Expression.Lambda(MyProperty, MyObject);
var MyMethod = Expression.Call(typeof(Enumerable), ascending ? "OrderBy" : "OrderByDescending", new[] { typeof(T), MyLamda.Body.Type }, MyEnumeratedObject, MyLamda);
var MySortedLamda = Expression.Lambda<Func<IEnumerable<T>, IOrderedEnumerable<T>>>(MyMethod, MyEnumeratedObject).Compile();
return MySortedLamda(items);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With