假设您的输入数据如下所示:
IEnumerable<Tuple<string, int>> firstSequence = ..., secondSequence = ...;
如果字符串在每个序列中都是唯一的(即在任何一个序列中都不能超过一个 {"A", XXX}),您可以join
这样:
var query = from tuple1 in firstSequence
join tuple2 in secondSequence on tuple1.Item1 equals tuple2.Item1
select Tuple.Create(tuple1.Item1, tuple1.Item2 + tuple2.Item2);
您可能还想考虑使用 a group by
,如果这种唯一性不成立,这将更合适:
var query = from tuple in firstSequence.Concat(secondSequence)
group tuple.Item2 by tuple.Item1 into g
select Tuple.Create(g.Key, g.Sum());
如果两者都不是您想要的,请更准确地阐明您的要求。
编辑:在您澄清这些是字典之后 - 您现有的解决方案非常好。这是另一种选择join
:
var joined = from kvp1 in dict1
join kvp2 in dict2 on kvp1.Key equals kvp2.Key
select new { kvp1.Key, Value = kvp1.Value + kvp2.Value };
var result = joined.ToDictionary(t => t.Key, t => t.Value);
或流利的语法:
var result = dict1.Join(dict2,
kvp => kvp.Key,
kvp => kvp.Key,
(kvp1, kvp2) => new { kvp1.Key, Value = kvp1.Value + kvp2.Value })
.ToDictionary(a => a.Key, a => a.Value);