Group objects and add values

1

I have a ListaBid class with multiple objects, in this class there are attributes Partnumber(Chave) , Quantidade SaldoPartnumber .

I can have X objects with partnumber Y and other X objects with% co_of% Z

I would like to sum the SaldoPartnumber attribute of all items that have the value of Partnumber .

var itensPedido = (from l in listaBID
                   select new Pedido.sItemPedido
                   {
                       CodigoProduto = l.Partnumber,
                       SaldoPartnumberSap = l.SaldoPartnumberSap,
                       Saldo = l.Saldo,
                   }).ToList();
    
asked by anonymous 11.09.2017 / 16:46

1 answer

2

Just do a% simple%

var groupped = itensPedido.GroupBy(x => x.CodigoProduto)
                          .Select(g => new 
                          { 
                              Chave = g.Key, 
                              Itens = g.ToList(),
                              Total = g.Count(),
                              Soma = g.Sum(x => x.SaldoPartnumberSap),
                          });

A complete example - see working in .NET Fiddle :

using static System.Console;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    private static List<ListaBid> _lista = new List<ListaBid>
    {
        new ListaBid { Partnumber = "A01", SaldoPartnumberSap = 10 },
        new ListaBid { Partnumber = "A02", SaldoPartnumberSap = 05 },
        new ListaBid { Partnumber = "A01", SaldoPartnumberSap = 11 },
        new ListaBid { Partnumber = "A02", SaldoPartnumberSap = 15 }
    };

    public static void Main()
    {
        var itensPedido = (from l in _lista
                           select new 
                           {
                               CodigoProduto = l.Partnumber,
                               SaldoPartnumberSap = l.SaldoPartnumberSap,
                               Saldo = l.Saldo,
                           }).ToList();

        var groupped = itensPedido.GroupBy(x => x.CodigoProduto)
                                  .Select(g => new 
                                          { 
                                              Chave = g.Key, 
                                              Itens = g.ToList(),
                                              Total = g.Count(),
                                              Soma = g.Sum(x => x.SaldoPartnumberSap),
                                          });

        foreach(var g in groupped)
        {
            WriteLine($"{g.Chave} - Total: {g.Total} - Soma: {g.Soma}");            
        }
    }
}

class ListaBid 
{
    public string Partnumber { get; set; }
    public int SaldoPartnumberSap { get; set; }
    public int Saldo { get; set; }  
}
    
11.09.2017 / 17:00