lambda error with Join when placing a Groupby

Asked

Viewed 38 times

1

In this lambda, is giving error in select in t1 and t2. If placed Key says it does not recognize Totalliquido and the fields in t2. If removed Groupby works.

public List<LiberacaoItensDTO> GetLibItems(double id)
        {
            var lista = contexto.Liberacoes
                .Join
                (
                    contexto.ItensLibs,
                    t1 => t1.IdOrcamento,
                    t2 => t2.IdOrcamento,
                    (t1, t2) => new { t1, t2 }
                )                
                .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento && a.t1.IdOrcamento == id)
                .GroupBy(gb => new { gb.t1.IdOrcamento })
                .Select(item => new LiberacaoItensDTO
                {
                    TotalVenda = item.t1.TotalLiquido,
                    TotalLucro = item.t2.Total - (item.t2.Qtde*item.t2.Custo)
                }).ToList();

            //double totallucro = lista.Sum(t => t.TotalLucro);
           // lista.ForEach(t => t.TotalLucro = totallucro);

            return lista;
        }

1 answer

3


When Voce uses the GroupBy You have a list of groups. In order to understand, in your case, Voce will have so many groups depending on the number of budget ids.

If you haven’t noticed, you can check that the GroupBy returns IEnumerable<IGrouping<TKey, TSource>>, or a sequence of groups. Each group has a property Key which corresponds to the key used to form each group. As you can imagine there could be more than one element in each group.

Therefore the solution depends on its logic. If you know that each group can only have one element, the best one may be not to use the GroupBy. If you actually have several elements, you will need to change your code.

var lista = contexto.Liberacoes
    .Join
    (
        contexto.ItensLibs,
        t1 => t1.IdOrcamento,
        t2 => t2.IdOrcamento,
        (t1, t2) => new { t1, t2 }
    )                
    .Where(a => a.t1.IdOrcamento == a.t2.IdOrcamento && a.t1.IdOrcamento == id)
    .GroupBy(gb => new { gb.t1.IdOrcamento })
    .Select(group => new LiberacaoItensDTO
    {
        TotalVenda = group.Sum(item => item.t1.TotalLiquido),
        TotalLucro = group.Sum(item => item.t2.Total - (item.t2.Qtde*item.t2.Custo))
    }).ToList();
  • Hello Bruno, the idea and have a summation on the chart. What happens is that the table of items it prints in the graph the margin, as many times as it is the Qtde of items and need to show only one slice in the graph. So I created another DTO to load the profit from the table of items and I don’t even know if it will happen.

Browser other questions tagged

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