Dynamically create expressions lambdas + linq + OrderByDescending

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

Basically I want to convert queryResults.OrderByDescending(); in queryResults.OrderByDescending(myCustomGeneratedLambdaExp); where myCustomGeneratedLambdaExp will be a string containing x => x.name .

thanks

+2
source share
2 answers

I'm not sure exactly where you need dynamic lambda expressions. In any case, the best way to generate lambda expressions dynamically is to use expression trees. Here are two good tutorials on the topic:

This code generates a lambda expression similar to the one you requested ("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

+4
source

See Dynamic LINQ

Alternatively, you can use the switch, Reflection, or dynamic type operator in C # 4 to return a value based on the specified field name.

It was also done to death earlier.

+2
source

Source: https://habr.com/ru/post/1497844/


All Articles