动态LINQ查询ExpandoObject? [英] Dynamic LINQ querying of an ExpandoObject?
问题描述
有没有办法使用LINQ动态查询库(System.Linq.Dynamic)根据ExpandoObject的属性来评估一个条件?以下代码在 var e ...
行中引发异常,表示ExpandoObject类型中不存在属性或字段重量: -
Is there any way to use the LINQ dynamic query library (System.Linq.Dynamic) to evaluate a condition based on the properties of an ExpandoObject? The following code throws an exception on the "var e...
" line, saying "No property or field 'Weight' exists in type ExpandoObject":-
const string TestCondition = "MyStateBag.Foo >= 50 && MyStateBag.Bar >= 100";
dynamic myStateBag = new ExpandoObject();
myStateBag.Foo = 70;
myStateBag.Bar = 100;
var p = Expression.Parameter(typeof(ExpandoObject), "MyStateBag");
var e = DynamicExpression.ParseLambda(new[] { p }, null, TestCondition);
var result = e.Compile().DynamicInvoke(myStateBag);
Assert.IsTrue(result);
替代方法是将statebag作为字典实现,但这将导致略更详细的条件字符串,例如 MyStateBag [Foo]> = 50&& MyStateBag [Bar]> = 100
。由于这将被用作用户脚本环境的基础,所以如果可以实现,我更喜欢使用更简单的ExpandoObject语法。
The alternative would be to implement the "statebag" as a dictionary, but this will result in a slightly more verbose condition string, e.g. MyStateBag["Foo"] >= 50 && MyStateBag["Bar"] >= 100
. As this is going to be used as the basis of a user scripting environment, I would prefer the simpler ExpandoObject syntax if it's possible to achieve.
推荐答案
不直接动态LINQ库归结为表达式树,表达式树不直接支持动态。很可能,动态查询库正在使用 Expression.PropertyOrField
来处理 .Foo
等,而将不能使用动态
。
Not directly. The dynamic LINQ library boils down to an expression-tree, and expression trees do not directly support dynamic. Most likely, the dynamic query library is using Expression.PropertyOrField
to handle .Foo
etc, and that will not work with dynamic
.
您可能会/ /或者写一个自定义表达式解析器,如果发现该参数是一个字典,将替换为大量查找代码;不过没有乐趣。
You could perhaps write a custom expression parser that replaces this with lots of lookup code if it finds the parameter is a dictionary; not fun, though.
这篇关于动态LINQ查询ExpandoObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!