Using LINQ you can group the items by code and add the amount in each group. However, LINQ is only available from version 3.5 and in some cases we need to work with previous versions, so I also made a solution grouping and summing using a Dictionary
as a key/value structure for grouping items by code and adding quantities directly to the item value in the dictionary.
With LINQ
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
List<Teste> lstTeste = new List<Teste>
{
new Teste {Codigo = 1, Quantidade = 10},
new Teste {Codigo = 2, Quantidade = 10},
new Teste {Codigo = 1, Quantidade = 10},
new Teste {Codigo = 3, Quantidade = 10},
new Teste {Codigo = 2, Quantidade = 10}
};
List<Teste> lstAgrupado = lstTeste
.GroupBy(i => i.Codigo)
.Select(j => new Teste()
{
Codigo = j.First().Codigo,
Quantidade = j.Sum(ij => ij.Quantidade)
})
.ToList();
}
}
public class Teste
{
public int Codigo { get; set; }
public int Quantidade { get; set; }
}
}
Linless
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
List<Teste> lstTeste = new List<Teste>
{
new Teste {Codigo = 1, Quantidade = 10},
new Teste {Codigo = 2, Quantidade = 10},
new Teste {Codigo = 1, Quantidade = 10},
new Teste {Codigo = 3, Quantidade = 10},
new Teste {Codigo = 2, Quantidade = 10}
};
Dictionary<int, Teste> agrupamentoSomado = new Dictionary<int, Teste>();
foreach (Teste item in lstTeste)
{
if (agrupamentoSomado.ContainsKey(item.Codigo))
{
agrupamentoSomado[item.Codigo].Quantidade += item.Quantidade;
}
else
{
agrupamentoSomado.Add(item.Codigo, item);
}
}
List<Teste> lstAgrupado = new List<Teste>(agrupamentoSomado.Values);
}
}
public class Teste
{
public int Codigo { get; set; }
public int Quantidade { get; set; }
}
}
Christian, try to explain a little of the logic you adopted when posting a reply. And if you don’t have LINQ available I suggest using
Dictionary
;)– MFedatto
I honestly had never used Linq. How much logic seemed so "silly" that I didn’t even find it necessary
– Christian Beregula
It’s a matter of good practice, Christian. What may be trivial to you may not be trivial to other people. To whoever asked the question,.
– MFedatto