c# - Joining two dictionaries in linq -
suppose have 2 distinct dictionaries dictionary<string,string> da , dictionary<string,int> db
db holds counts of sub-level items
var db = new dictionary<string,int?>{{"sub1",10},{"sub2",30},{"sub3",70}...}; where da holds mapping of sub-level top level:
var da = new dictionary<string,string>{{"sub1","top1"},{"sub2","top1"},{"sub3","top2"}}; if want aggregate numbers @ top level,
{{"top1",40},{"top2",70}...} how go in linq? help!
here how can it:
var result = da .groupby(x => x.value) .todictionary( g => g.key, g => g.select(kvp => kvp.key).sum(sub => db[sub])); basically, group da value (which "top1" , "top2").
then such grouping, create dictionary. key such dictionary items key of grouping (e.g. "top1").
to calculate value each item in new dictionary, first select subs each group "sub1" , "sub2" , use db dictionary counts each 1 of them , calculate sum.
if db dictionary dictionary<string,int?>, need handle null values using getvalueordefault method this:
var result = da .groupby(x => x.value) .todictionary( g => g.key, g => g.select(kvp => kvp.key).sum(sub => db[sub].getvalueordefault()));
Comments
Post a Comment