Group objects and add values

Asked

Viewed 1,012 times

1

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

I can have X objects with the partnumber Y and other X objects with Partnumber Z

I would like to sum up the attribute Saldopartnumber of all items that has the value of Partnumber equal.

Exemplo da classe

var itensPedido = (from l in listaBID
                   select new Pedido.sItemPedido
                   {
                       CodigoProduto = l.Partnumber,
                       SaldoPartnumberSap = l.SaldoPartnumberSap,
                       Saldo = l.Saldo,
                   }).ToList();

1 answer

2


Just make a GroupBy 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 on . 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; }  
}

Browser other questions tagged

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