2

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.

Thanks

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
byte_slave
  • 1,368
  • 1
  • 12
  • 24

2 Answers2

4

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)),
    targetParameter
);
return lambda.Compile();

hope this helps

jpbochi
  • 4,366
  • 3
  • 34
  • 43
2

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

Community
  • 1
  • 1
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
  • Thanks a lot for your input! My point is to avoid switch code and reflection make it slower. – byte_slave Nov 03 '09 at 16:02
  • Yes, makes sense. Good luck with it. Using dynamic and/or Iron* is more clean than Dynamic LINQ or reflection.emit or Expression.Compile though if you're trying to keep your code maintainable and Clean IMO. – Ruben Bartelink Nov 03 '09 at 17:25