How to combine dictionaries in Linq? -
i'm new linq. have code this:
public class info { public dictionary<string,int> wordfrequency; } list<data> datalist;
what want 1 aggregated dictionary combined wordfrequency whole list of info objects. know how using loops (iterate on list, iterate on each dictionary), question is, linq syntax this? give thanks you.
edit: here (untested) looping approach, can see mean.
public static dictionary<string, int> combine() { dictionary<string, int> result; foreach (data info in datalist) { foreach (string key in data.wordfrequencies.keys) { if(!result.containskey(key)) result[key] = 0; result[key] += data.wordfrequencies[key]; } } }
so want flatten dictionaries single one, has no duplicate keys - of course?
you can utilize enumerable.selectmany
flatten , enumerable.groupby
grouping keys.
dictionary<string, int> allwordfrequency = datalist .selectmany(d => d.wordfrequency) .groupby(d => d.key) .todictionary(g => g.key, g => g.sum(d => d.value));
i have presumed want sum frequencies.
linq
No comments:
Post a Comment