Add subitems between groups with linq

1

How can I perform calculations between subitems of a group by query in linq? Here's an example:

Linq Query

var listPlanoDeContas = (from t in _planoDeContasRepository.GetAll()
                         orderby t.Month ascending
                         group t by t.DfpChartOfAccounts into dfpGroup
                         select dfpGroup).ToList();

To illustrate, this query returns something like:

Plano de Contas      |    Mês 1    |    Mês 2     |    Mês 3    | ...

Receitas Totais           10000,00        13000,00      8000,00
Deduções                    878,00         1020,00       780,00
Custos                     1345,00         1478,00       850,00
Despesas                   3789,00         4342,00      1678,00
______________________________________________________________________
Saldo de Caixa                ?               ?             ?

I need to find the cash balance . So I would like some help to calculate via Linq or Lambda the values between each item in the chart of accounts per month. That is:

Total Revenue of the Month 1 - Deductions of the Month 1 - Costs of the Month 1 - Expenses of the Month 1

Thank you in advance.

    
asked by anonymous 23.10.2018 / 18:56

2 answers

1

I have decided as follows:

//Fiz uma consulta geral no DB e agrupei por mês
var qry = _planoDeContasRepository.GetAll()
	 .GroupBy(x => x.Month).ToList();

//Pecorre a consulta aplicando o filtro e realizando o cálculo
foreach(var i in qry)
{
    var valorReceita = i.Where(x => x.Categoria.Equals("Receita")).Select(x => x.Valor).ToList();
    decimal valor = Convert.ToDecimal(valorReceita[0]);
    
    var somaTotalPorMes = i.Sum(x => x.Valor);

    decimal saldo = Convert.ToDecimal(somaTotalPorMes) - valor;
}

//Retorno o saldo e....
    
09.11.2018 / 22:44
1

Note that in the example below I'm using a sample class and hypothetical fields of its class.

But I believe that only the code below meets your need, if your return on listPlanoDeContas is what you posted in the question.

SaldoCaixa =
new TotaisSaldoCaixa
{
    Total_Janeiro = listPlanoDeContas
        .Select(c => c.ReceitaJan - c.DeducoesJan - c.CustosJan - c.DespesasJan).SingleOrDefault(),

    Total_Fevereiro = listPlanoDeContas
        .Select(c => c.ReceitaFeb - c.DeducoesFeb - c.CustosFeb - c.DespesasFeb).SingleOrDefault(),

    Total_Marco = listPlanoDeContas
        .Select(c => c.ReceitaMar - c.DeducoesMar - c.CustosMar - c.DespesasMar).SingleOrDefault(),
    //Restante dos meses...
};
    
08.11.2018 / 19:59