所以我有一个定义为这样的并发字典
ConcurrentDictionary<string, ConcurrentDictionary<string, ConcurrentDictionary<string, SomeObject>>>();
我知道这似乎有点复杂,但结构是有效的......
现在我的问题是我已经为x个不同来源说了x个这些词典的实例,为了统计目的,他们需要合并/合并/聚合成一个相同结构的单个词典...
有关最佳方法的任何想法吗?我知道我可以创建一个相同结构的新词典;循环遍历每个词典以进行合并,并在每个级别检查新词典中的那些键等,并根据该决定的结果添加或更新...
但这对我来说似乎有点笨拙......任何可以伸出援助之手的LINQ天才?
[注意 - 我刚做了一个重要的编辑 - 输出字典与输入字典完全相同]
答案 0 :(得分:1)
LINQ在这里没有帮助,因为您不想查询集合而是操纵集合。
正如上面的评论所述,使用ConcurrentDictionary<Tuple<string, string, string>, SomeObject>
可以简化一些事情。您可以执行以下操作:
using MyDict = ConcurrentDictionary<Tuple<string, string, string>, SomeObject>;
MyDict Merge(IEnumerable<MyDict> dicts)
{
MyDict result = new MyDict();
foreach (var dict in dicts)
{
foreach (var kvp in dict)
{
result.AddOrUpdate(
kvp.Key, // If the key does not exist, add the value;
kvp.Value, // otherwise, combine the two values.
(key, value) => Combine(value, kvp.Value)
);
}
}
return result;
}