SelectMany() 无法扁平化词典类型

BUG反馈 · 531 次浏览
咿呀杀杀 创建于 2024-05-09 14:20

例子,把一个 List<Dictionary<string, string>> 展开为 KeyValuePair 列表,结果会报错:
Error:解析表达式错误。
Oops! No applicable member has been found for the expression. The error occurred for expression "." at position 315 near ".SelectMany(d => d)

var dictList = new List<Dictionary<string, string>>
{
    new Dictionary<string, string>()
    {
        {"key1", "value1"},
        {"key2", "value2"}
    },
    new Dictionary<string, string>()
    {
        {"key3", "value3"},
        {"key4", "value4"}
    }
};


var mergedDict = dictList
	.SelectMany(d => d)
	.ToDictionary(kv => kv.Key, kv => kv.Value);

回复内容
CL 2024-05-09 15:00
#1

试了一下,确实不行。可能是表达式引擎的bug,我去反馈一下。

作为备选,可以用下面的代码实现合并词典。

Dictionary<string, string> mergedDictionary = new Dictionary<string, string>();

        foreach (var dict in dictionaries)
        {
            foreach (var pair in dict)
            {
                // 使用索引器赋值,这将添加新的键或更新现有键的值
                mergedDictionary[pair.Key] = pair.Value;
            }
        }
回复主贴