dynamically create lambdas expressions + linq + OrderByDescending

别说谁变了你拦得住时间么 提交于 2019-12-02 01:56:52

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

Ruben Bartelink

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!