Merge two items of an Ilist into one item by Id

Asked

Viewed 356 times

2

In my class has:

Id 
Venda 
Devolucao

I have a IList of that class, and in that IList has

[0] classe Id = 100, Venda = 230.00, Devolucao = 0;
[1] classe Id = 100, Venda = 0, Devolucao = 50.00;
[2] classe Id = 101, Venda = 515.00, Devolucao = 0;
[3] classe Id = 101, Venda = 0, Devolucao = 42.00;

How to gather this information by Id? To stay:

[0] classe Id = 100, Venda = 230.00, Devolucao = 50.00;
[1] classe Id = 101, Venda = 515.00, Devolucao = 42.00;

class VendaDevolucao
{
    public virtual int Id { get; set; }
    public virtual double Venda { get; set; }
    public virtual double Devolucao { get; set; }
}

IList<VendaDevolucao> vendas = new List<VendaDevolucao>();

VendaDevolucao venda1 = new VendaDevolucao();
venda1.Id = 100;
venda1.Venda = 230.00;
venda1.Devolucao = 0;
vendas.Add(venda1);

VendaDevolucao venda2 = new VendaDevolucao();
venda2.Id = 100;
venda2.Venda = 0;
venda2.Devolucao = 50.00;
vendas.Add(venda2);

VendaDevolucao venda3 = new VendaDevolucao();
venda3.Id = 101;
venda3.Venda = 515.00;
venda3.Devolucao = 0;
vendas.Add(venda3);

VendaDevolucao venda4 = new VendaDevolucao();
venda4.Id = 101;
venda4.Venda = 0;
venda4.Devolucao = 42.00;
vendas.Add(venda4);
  • Enter the code you already have. [mcve]. Specifies better what it would be like to join.

  • I put an example... is not the real situation, just wanted to leave in a more generic way

  • "aggregate" information where Id is equal

2 answers

3


Makes a grouping with Linq (System.Linq), use the Id to group and add the values of the other two fields:

Example

var items = vendas.GroupBy(c => c.Id)
      .Select(s => new {
         Id = s.Key,
         Venda = s.Sum(v => v.Venda),
         Devolucao = s.Sum(d => d.Devolucao)
      }).ToList();

Demo

or

var items = vendas.GroupBy(c => c.Id)
      .Select(s => new VendaDevolucao  {
         Id = s.Key,
         Venda = s.Sum(v => v.Venda),
         Devolucao = s.Sum(d => d.Devolucao)
      }).ToList();

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.