Maetness
Maetness

Reputation: 87

How to merge 2 Dictionaries into a third that consists of {Key=Value(Dict1), Value=Value(Dict2)}

I am trying to merge 2 Dictionaries.

The first one consists of an ID and a Title, so for instance: {2, Error}.

The second one consists of an ID and the frequency in which the ID occurs: {2, 3}.

I want to create a dictionary that looks like this: {Error, 3}.

Is this possible?

My code thus far works only if there are no duplicates ... I want to just add the frequency number of the duplicate ID to the already saved frequency of the previous occurrence of the same ID. So e.g. if in dict2 for some reason there exists {2, 3} and {2, 5} the result in dict3 should be {Error, 8}.

foreach (var item in dict2)
{
    foreach(var entry in dict1)
    {
        if (item.Key.Equals(entry.Key))
        {
            dict3.Add(entry.Value.ToString(), (int)item.Value);                       
        }
    }
}

Upvotes: 0

Views: 55

Answers (1)

Sefe
Sefe

Reputation: 14007

You can use LINQ:

var combinedDictQry =
    from entry1 in dictionary1
    from entry2 in dictionary2
    where entry1.Key == entry2.Key
    select new { Key = entry1.Value, Value = entry2.Value };
var combinedDict = combinedDictQry.ToDictonary(entry => entry.Key, entry => entry.Value);

This will serve you well for smaller dictionaries (ie. for most practical purposes). If you need to process larger amounts of data, you might get performance issues and you will have to access the values of the second dictionary with TryGetValue to make use of the dictionary's better access performance.

If you expect duplicate values in dictionary1, .ToDictionary will not work, because duplicate keys are not allowed in a dictionary. You can however create a lookup. Duplicate keys will be merged and the values can be enumerated:

var combinedLookup = combinedDictQry.ToLookup(entry => entry.Key, entry => entry.Value);

Upvotes: 2

Related Questions