我有一组像这样的词典(希望这很有意义,在飞行中做)
dim dic as new ienumerable(of dictionary(of integer, double))= _
{dictionary(of integer, double) = new { {1, 0.5}, {5, 0.75} } _
,dictionary(of integer, double) = new { {1, 0.3}, {4, 0.46} }}
我希望获得dictionary
(使用linq)相同键的总和,如此
dictionary(of integer, double) = { {1, 0.8}, {4, 0.46}, {5, 0.75} }
因此,换句话说,我想group
keys
并添加values
分组的项目。
我可以使用for loop
轻松完成此操作,但我正在尝试学习linq,并希望使用它来解决问题。谁能给我一些关于如何到达那里的提示?
答案 0 :(得分:1)
Dictionary<int, int> dict1 = new Dictionary<int, int>() {{1,9},{2,10},{3,11} };
Dictionary<int, int> dict1 = new Dictionary<int, int>() {{1,9},{2,10},{3,11} };
Dictionary<int, int> dict2 = new Dictionary<int, int>() { { 1, 9 }, { 2, 10 }, { 3, 11 } };
Dictionary<int, int> dict3 = new Dictionary<int, int>() { { 1, 9 }, { 2, 10 }, { 3, 11 } };
List<Dictionary<int, int>> list = new List<Dictionary<int, int>> {dict1,dict2,dict3 };
Dictionary<int, int> dictionary = new Dictionary<int, int>();
list.SelectMany(a => a).GroupBy(a => a.Key).ToList().ForEach(el=>dictionary.Add(el.Key,el.Sum(sm=>sm.Value)));
我没有VB.net的知识,但这是在C#中。我希望这会有所帮助。