如何使用Linq表达式访问字典项

12

我希望使用Linq表达式构建一个Lambda表达式,能够使用字符串索引来访问“属性包”样式的字典中的项目。我正在使用 .Net 4。

    static void TestDictionaryAccess()
    {
        ParameterExpression valueBag = Expression.Parameter(typeof(Dictionary<string, object>), "valueBag");
        ParameterExpression key = Expression.Parameter(typeof(string), "key");
        ParameterExpression result = Expression.Parameter(typeof(object), "result");
        BlockExpression block = Expression.Block(
            new[] { result },               //make the result a variable in scope for the block
            Expression.Assign(result, key), //How do I assign the Dictionary item to the result ??????
            result                          //last value Expression becomes the return of the block
        );

        // Lambda Expression taking a Dictionary and a String as parameters and returning an object
        Func<Dictionary<string, object>, string, object> myCompiledRule = (Func<Dictionary<string, object>, string, object>)Expression.Lambda(block, valueBag, key).Compile();

        //-------------- invoke the Lambda Expression ----------------
        Dictionary<string, object> testBag = new Dictionary<string, object>();
        testBag.Add("one", 42);  //Add one item to the Dictionary
        Console.WriteLine(myCompiledRule.DynamicInvoke(testBag, "one")); // I want this to print 42
    }
在上面的测试方法中,我想将字典项值,即testBag["one"],分配到结果中。请注意,我已经将传入的键字符串分配给结果,以演示Assign调用。
1个回答

19
你可以使用以下代码来访问字典的Item属性。
Expression.Property(valueBag, "Item", key)

以下是应该解决问题的代码更改。

ParameterExpression valueBag = Expression.Parameter(typeof(Dictionary<string, object>), "valueBag");
ParameterExpression key = Expression.Parameter(typeof(string), "key");
ParameterExpression result = Expression.Parameter(typeof(object), "result");
BlockExpression block = Expression.Block(
  new[] { result },               //make the result a variable in scope for the block           
  Expression.Assign(result, Expression.Property(valueBag, "Item", key)),
  result                          //last value Expression becomes the return of the block 
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接