chi
chi

Reputation: 501

Joining two dictionaries in linq

Suppose that I have two distinct dictionaries Dictionary<string,string> Da and Dictionary<string,int> Db

Db holds the counts of sub-level items

var Db = new Dictionary<string,int?>{{"sub1",10},{"sub2",30},{"sub3",70}...};

where Da holds the mapping of sub-level to top level:

var Da = new Dictionary<string,string>{{"sub1","top1"},{"sub2","top1"},{"sub3","top2"}};

If I want to aggregate the numbers at top level,

{{"top1",40},{"top2",70}...}

how would I go about it in linq? Thanks for your help!

Upvotes: 2

Views: 1094

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27861

Here is how you can do it:

var result =
    Da
    .GroupBy(x => x.Value)
    .ToDictionary(
        g => g.Key,
        g => g.Select(kvp => kvp.Key).Sum(sub => Db[sub]));

Basically, you group Da by the value (which is like "top1" and "top2").

Then from such grouping, you create a dictionary. The key for such dictionary items would be the key of the grouping (e.g. "top1").

To calculate the value for each item in the new dictionary, we first select the subs for each group like "sub1" and "sub2" and use the Db dictionary to get the counts for each one of them and then calculate the sum.

If the Db dictionary is actually Dictionary<string,int?>, then you need to handle null values by using the GetValueOrDefault method like this:

var result =
    Da
    .GroupBy(x => x.Value)
    .ToDictionary(
        g => g.Key,
        g => g.Select(kvp => kvp.Key).Sum(sub => Db[sub].GetValueOrDefault()));

Upvotes: 4

Related Questions