动态创建的lambda表达式LINQ + + OrderByDescending [英] dynamically create lambdas expressions + linq + OrderByDescending

查看:197
本文介绍了动态创建的lambda表达式LINQ + + OrderByDescending的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以创建一个动态的lambda表达式通过在LINQ里面我排序依据功能使用?

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

我基本上要转变 queryResults.OrderByDescending (); queryResults.OrderByDescending(myCustomGeneratedLambdaExp); ,其中 myCustomGeneratedLambdaExp 应是一个字符串containning X => x.name

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

感谢

推荐答案

我不知道在哪里你究竟需要动态lambda表达式。不管怎么说,动态生成lambda表达式的最好方法是使用表达式树。以下是关于这个问题的两个很好的教程:

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:

http://marlongrech.wordpress.com/2008/01/08/working-with-expression-trees-part-1/

这代码生成一个lambda表达式就像你问一个(X => x.name):

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

这篇关于动态创建的lambda表达式LINQ + + OrderByDescending的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆