Question

Je veux construire une expression Lambda en utilisant des expressions Linq qui est en mesure d'accéder à un élément dans un style « sac de propriété » Dictionnaire en utilisant un indice de chaîne. J'utilise .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
    }

Dans la méthode d'essai ci-dessus, je veux affecter la valeur de l'élément Dictionnaire savoir testBag [ « one »] dans le résultat. Notez que j'ai assigné la chaîne transmise clé dans le résultat de démontrer l'appel Assign.

Était-ce utile?

La solution

Vous pouvez utiliser ce qui suit pour accéder à la propriété d'objet de la Dictionary

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

Voici le changement de code qui devrait faire l'affaire.

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 
);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top