c# - 如何使用 Linq 表达式访问字典项

标签 c# lambda linq-expressions

我想使用 Linq 表达式构建一个 Lambda 表达式,该表达式能够使用字符串索引访问“属性包”样式字典中的项目。我正在使用 .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 调用。

最佳答案

您可以使用以下方法访问 Dictionary 的 Item 属性

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

关于c# - 如何使用 Linq 表达式访问字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3085955/

相关文章:

c# - 可靠地检测 C# 表达式树中编译器生成的类

c# - 代码清理在插值字符串中添加空格

c# - 使用 C# 合并两个列表

java - 使用 lambda 表达式处理异常

c# - C# 捕获外部变量中的 Lambdas - 请解释书中的示例 "C# in nutshell 5.0"

c# - .Net Core 本地化 View : IViewLocalizer inside Linq expression

c# - Entity Framework 代码首先为正数添加约束

c# - 如何在linq中比较两组数据并返回公共(public)数据?

linq - 在 LINQ Lambda 表达式中使用 GroupBy、Count 和 Sum

c# - Stateful Expression 访问者多次运行问题