如何使用Linq表达式访问字典项 [英] How do I access a Dictionary Item using Linq Expressions

查看:47
本文介绍了如何使用Linq表达式访问字典项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Linq Expressions构建Lambda表达式,该表达式可以使用String索引访问属性包"样式字典中的项目.我正在使用.Net 4.

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
    }

在上述测试方法中,我想将Dictionary项的值即testBag ["one"]分配给结果.请注意,我已将传入的Key字符串分配到结果中,以演示Assign调用.

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.

推荐答案

您可以使用以下内容访问Dictionary

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 
);

这篇关于如何使用Linq表达式访问字典项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆