Pick all fields of a class using Lambda + Group By

Asked

Viewed 304 times

1

I have a list:

produtosCompletos = (from f in estoques
                     join p in produtos on f.idProduto equals p.id
                     join c in classes on f.idClasse equals c.id
                     select new produtoCompleto()
                     {
                         idUnidade = f.idUnidade,
                         descricao = p.descricao,
                         classe = c.descricao,
                         lote = f.lote,
                         dtValidade = f.dtValidade,
                         quant = f.quant
                     }).ToList();

With this list, I want to add up the value of Uant grouped by Description. I am doing so:

        var result =
            (from p in produtosCompletos
            group p by p.descricao
            into g
            select new produtoCompleto()
            {
                idUnidade = //não sei como mostrar aqui :/
                descricao = g.Key,
                quant = g.Sum(x => x.quant)
            }).ToList();

As you can see above, I can only catch the descricao and the quant, the other fields I don’t know how to catch

2 answers

5

To make a group by with several fields in the Lake, you need to declare all the desired fields in your group by, would be as follows:

 var result =
            (from p in produtosCompletos
            group p by new {p.descricao, p.idUnidade }
            into g
            select new produtoCompleto()
            {
                idUnidade = g.Key.idUnidade 
                descricao = g.Key.descricao,
                quant = g.Sum(x => x.quant)
            }).ToList();

You can access your variables later through the Key

1


You need to take the first item from the group and get the id.

var result =
            (from p in produtosCompletos
             group p by p.descricao
            into g
             select new produtoCompleto()
             {
                 idUnidade = g.First().idUnidade,
                 descricao = g.Key,
                 quant = g.Sum(x => x.quant)
             }).ToList();

Browser other questions tagged

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