How do I access a Dictionary Item using Linq Expressions
Asked Answered
E

1

12

I want to build a Lambda Expression using Linq Expressions that is able to access an item in a 'property bag' style Dictionary using a String index. I am using .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
    }

In the above test method, I want to assign the Dictionary item value i.e. testBag["one"] into the result. Note that I have assigned the passed in Key string into the result to demonstrate the Assign call.

Excursionist answered 21/6, 2010 at 15:22 Comment(0)
E
19

You can use the following to access the Item property of the Dictionary

Expression.Property(valueBag, "Item", key)

Here is the code change that should do the trick.

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 
);
Enriquetaenriquez answered 21/6, 2010 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.