包含重复键的案例的最通用解决方案可以使用GroupBy和Sum LINQ方法实现:
var result = firstCollection .Concat(secondCollection) .GroupBy(x => x.Name) .Select(g => new Foo { Name = g.Key, Value = g.Sum(f => f.Value) }); // Foo is an example of your element class. You can use anonymous classes //.Select(g => new { Name = g.Key, Value = g.Sum(f => f.Value) });
该解决方案的算法复杂度为O(n).
如果您希望获得最大性能,可以使用序数字符串比较:
var result = firstCollection .Concat(secondCollection) .GroupBy(x => x.Name, x => x, StringComparer.Ordinal) .Select(g => new Foo { Name = g.Key, Value = g.Sum(f => f.Value) });