合并两个集合并对重复项的字段求和

时间:2016-11-25 14:40:24

标签: c#

我有两个系列:

public interface ISomeNeededInterface
{
    string Name { get; set; }
    Guid Guid { get; set; }
}

public class Order : ISomeNeededInterface
{
    public string Name { get; set; }
    public Guid Guid { get; set; }
}

public class SalesOrder
{   
  public string Name { get { return Item.Name;} }
  public double Price { get; set; }
  public int Quantity { get; set; }
  private ISomeNeededInterface Item { get; private set; }

  public SalesOrder(ISomeNeededInterface _item)
  {
    Item = _item;
    Price = _item.Pricce;
    Quantity = _item.Quantity;
  }   
}

List<SalesOrder> Orders1 = new List<SalesOrder>()
  {
     new SalesOrder(new Order {"Ballon1", Guid.NewGuid();}, 2.54, 1),
     new SalesOrder(new Order {"Ballon2", Guid.NewGuid();}, 2.54, 1),
  };

List<SalesOrder> Orders2 = new List<SalesOrder>()
  {
     new SalesOrder(new Order {"Ballon1", Guid.NewGuid();}, 2.54, 2),
     new SalesOrder(new Order {"Ball", Guid.NewGuid();}, 4.52, 1)
  };

如何将两个集合合并为一个集合,以及合并那些重合的元素&#34;名称&#34;字段?同时,对于元素,合并的名称必须是字段&#34; Quantity&#34;的总和。最后一定是

List<SalesOrder> SummOrders = {"Ballon1", 2.54, 3, SOME_Item; "Ballon2", 2.54, 1, SOME_Item ;  "Ball", 4.52, 1, SOME_Item }

编辑:需要澄清简单问题?好的,有更多真实的&#34;编辑&#34;

1 个答案:

答案 0 :(得分:7)

使用ConcatGroupBySum

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();

考虑Name可能相同,但它有不同的Price,所以它实际上是一个不同的产品。然后,您可以按包含两个属性的匿名类型进行分组(理想情况下,您使用唯一标识符):

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();