2010-06-21 40 views
6

我想使用Linq Expressions構建一個Lambda表達式,該表達式可以使用String索引訪問「屬性包」樣式字典中的項目。我正在使用.Net 4如何使用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 
    } 

在上述測試方法中,我想將Dictionary項值即testBag [「one」]賦值給結果。請注意,我已將傳入的密鑰字符串分配給結果以演示分配呼叫。

回答

10

您可以使用以下方法來訪問的Dictionary

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

Item屬性下面是代碼的變化是應該做的伎倆。

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

謝謝克里斯,這是一種享受。 – 2010-06-22 03:03:12