i need to merge three dictionary collection, if key is same i want to add value.
Result is like
One - 5+5 =10
two - 10+20=30
three - 7
four - 2
five - 8
six - 2
Dictionary<string, int> d1 = new Dictionary<string, int>();
d1.Add("one", 5);
d1.Add("two", 10);
d1.Add("three", 7);
Dictionary<string, int> d2 = new Dictionary<string, int>();
d2.Add("four", 2);
d2.Add("two", 20);
d2.Add("five", 8);
Dictionary<string, int> d3 = new Dictionary<string, int>();
d3.Add("one", 5);
d3.Add("six", 2);
Union: ignore the matching resultset.
var uQuery = (开发者_高级运维from a in d1 select a).Union(from b in d2 select b).GroupBy(grp=>grp.Key );
You should use Concat instead of Union. Union will treat the key value pair ["one", 5] as duplicated in d1 and d3, and therefore exclude one instance of it, giving this result:
- "one", 5
- "two", 30
- "three", 7
- "four", 2
- "five", 8
- "six", 2
var result = d1.Concat(d2.Concat(d3)).GroupBy(keyValuePair => keyValuePair.Key).ToDictionary(group => group.Key, grp => grp.Sum(kvp => kvp.Value));
or perhaps more readably:
var union = d1.Concat(d2.Concat(d3));
var groupBy = union.GroupBy(keyValuePair => keyValuePair.Key);
var result = groupBy.ToDictionary(group => group.Key, grp => grp.Sum(kvp => kvp.Value));
精彩评论