3
votes

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);

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.

1

1 Answers

3
votes

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.