2010-06-21 13 views
6

Je souhaite créer une expression Lambda à l'aide d'expressions Linq permettant d'accéder à un élément dans un dictionnaire de style 'sac de propriétés' en utilisant un index String. J'utilise .Net 4.Comment accéder à un élément de dictionnaire à l'aide d'expressions Linq

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 de clé dans le résultat pour démontrer l'appel Assign.

Répondre

10

Vous pouvez utiliser les éléments suivants pour accéder à la propriété Item 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 
); 
+0

Merci Chris, ça marche. –