Как получить доступ к элементу словаря с помощью выражений Linq

Я хочу создать лямбда-выражение с использованием выражений Linq, которое может получить доступ к элементу в словаре стиля «сумка свойств», используя индекс String. Я использую .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"]. Обратите внимание, что я назначил переданную строку Key в результат, чтобы продемонстрировать вызов Assign.


person Michael Dausmann    schedule 21.06.2010    source источник


Ответы (1)


Вы можете использовать следующее для доступа к свойству Item объекта Dictionary

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 
);
person Chris Taylor    schedule 21.06.2010