dynamically create lambdas expressions + linq + OrderByDescending

c# dynamic-linq lambda linq


how can I create a dynamic lambda expression to pass to use in my orderby function inside linq?

I basically want transform queryResults.OrderByDescending(); in queryResults.OrderByDescending(myCustomGeneratedLambdaExp); where myCustomGeneratedLambdaExp shall be a string containning x => x.name.


5/24/2012 12:18:42 PM

Accepted Answer

I'm not sure where exactly did you need dynamic lambda expressions. Anyways, the best way to generate lambda expressions dynamically is by using expression trees. Here are two good tutorials on the subject:

This code generates a lambda expression like the one you asked for ("x => x.name"):

MemberInfo member = typeof(AClassWithANameProperty).GetProperty("Name");

//Create 'x' parameter expression
ParameterExpression xParameter = Expression.Parameter(typeof(object), "x");

//Create body expression
Expression body = Expression.MakeMemberAccess(targetParameter, member);

//Create and compile lambda
var lambda = Expression.Lambda<LateBoundGetMemberValue>(
    Expression.Convert(body, typeof(string)),
return lambda.Compile();

hope this helps

5/24/2017 4:59:27 PM

Popular Answer

See Dynamic LINQ

Alternately, you can use a switch statement, Reflection or the dynamic type in C# 4 to return the value based on a supplied field name.

This has also been done to death previously

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow