Use Concat
, GroupBy
and Sum
:
List<SalesOrder> merged = Order1.Concat(Orders2)
.GroupBy(so => so.Name)
.Select(g => new SalesOrder(g.Key, g.First().Price, g.Sum(so => so.Quantity)))
.ToList();
Consider that the Name
could be equal but it has a different Price
, so it’s actually a different product. Then you could group by an anonymous type containing both properties (ideally you use a unique identifier):
List<SalesOrder> merged = Order1.Concat(Orders2)
.GroupBy(so => new { so.Name, so.Price })
.Select(g => new SalesOrder(g.Key.Name, g.Key.Price, g.Sum(so => so.Quantity)))
.ToList();
0
solved Merge two collections and sum the fields for duplicate items