Question

So I have a concurrent dictionary defined as such

 ConcurrentDictionary<string, ConcurrentDictionary<string, ConcurrentDictionary<string, SomeObject>>>();

I know that seems a little convoluted but the structure is valid...

Now my problem is that I have say x number of instances of these dictionaries for x different sources and for statistical purposes they need to be merged/amalgamated/aggregated into one single dictionary of the same structure...

Anyone any ideas on the best approach? I know I could create a new dictionary of the same structure; loop through each of the dictionaries to be amalgamated and at each level checking the new dictionary for those keys etc and adding or updating based on the result of that determination...

But that seems slightly unwieldy to me... any LINQ geniuses out there that could lend a hand?

[Note - I just made one important edit - the output dictionary is of the exact same structure as the input dictionaries]

Was it helpful?

Solution

LINQ doesn't help here, as you don't want to query a collection but manipulate one.

As said in the comments above, using a ConcurrentDictionary<Tuple<string, string, string>, SomeObject> would simplify things a bit. You could do the following then:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top