动态创建的表达式
我正在创建一个动态表达式,它将按某种规则(lambda exp.)对列表中的项目进行排序。 这是代码:
Expression<Func<String, String>> exp = o => o;
MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);
现在我想对特定数据执行先前创建的表达式来对其进行排序,但由于一些奇怪的异常(例如“Lambda 参数不在范围内”或“参数表达式无效”)而失败。
var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };
// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);
有人可以帮我解决这个问题吗?
I'm creating a dynamic expression, which will order items in a list by some rule (lambda exp.). This is the code:
Expression<Func<String, String>> exp = o => o;
MethodCallExpression orderByExp = Expression.Call(typeof(Enumerable), "OrderBy",
new Type[] { typeof(String), exp.Body.Type }, Expression.Parameter(typeof(IEnumerable<String>), "list"), exp);
Now I want to execute previously created expression on specific data to sort it, but it fails because of some strange exceptions like "Lambda Parameter not in scope" or "Argument expression is not valid".
var data = new String[] { "asdasdasd", "asdads", "123", "xcvxcvs", "ASDSD" };
// one of attempts: doesn't work
var result = data.AsQueryable().Provider.CreateQuery<String>(orderByExp);
Can somebody help me with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过属性对任何可枚举进行排序(无反射):
order any enumerable by a property(no reflection):
这是工作代码:
感谢专家
This is the working code:
thanks experts
我在使用 Linq 时遇到了几乎相同的问题,我决定编写一个扩展函数,其中一些想法取自这个问题的答案:
I had the nearly the same problem working with Linq, i decided to write a extension function, and some of the ideas were taken from the answers of this question:
您不只是调用有什么特殊原因吗:
您甚至需要在此处使用
IQueryable
吗? 我感觉我错过了一些大局。 您实际上要将其作为 LINQ to SQL(或 LINQ to Entities)的一部分来调用吗? 如果它只是在 LINQ to Objects 中,您不能只使用data.OrderBy(exp)
吗?基本上,更多的解释会有所帮助:)
Is there any particular reason you're not just calling:
Do you even need to use
IQueryable
here? I get the feeling I'm missing some of the big picture. Are you actually going to be calling this as part of LINQ to SQL (or LINQ to Entities)? If it's just within LINQ to Objects, can't you just usedata.OrderBy(exp)
?Basically, some more explanation would be helpful :)