Make calculation using LINQ

Asked

Viewed 147 times

2

I am developing a program in c#. In it I have three tables:

produto
{
    string idProduto;
    string descricao;
}

entrada
{
    string idProduto;
    int quant;
}

saida
{
    string idProduto;
    int quant;
}

and I want to create a class like this:

estoqueAtual
{
    string produto;
    int saldo; //onde saldo seria entrada.quant - saida.quant
}

How can I calculate the balance?

  • 1

    Could you improve your question? entering the information of which language you are working on and the products you have in the output class are the same as in the input class?

  • Okay, I’ve edited the question

  • I think the best way would be to leave the variable saldo product inside and do not see, at first, the need for a class to saída and entrada. You can create them as methods within product and thus they would update the variable of saldo.

  • Is LINQ in memory, LINQ to SQL or LINQ to Entities? Uses Entity Framework?

  • @Gypsy omorrisonmendez use Entity Framework

  • @leonardopessoa this database will be replicated, so I am preferring only to insert information than edit, to facilitate the time to replicate to other databases

  • More questions: you will trigger this manual calculation or it will be reactive, for example, made as this one is a Trigger, but within C#? The "tables" are mapped as Models? If yes, you can update the code with the Models?

  • @Ciganomorrisonmendez I don’t know if I understand well: as soon as I open the form, I will do the calculation and list in a grid. The tables are mapped yes. As for changing them, I don’t know if I can do it, because I’m still learning.

  • Ok, is your application Windows Forms or Web Forms? The calculation takes place in the grid or the inclusion/modification of information?

Show 4 more comments

1 answer

4


as you gave more details about your database schema or your entity mapping, so it is difficult to deliver something more optimized.

Then try the following query.:

var entradas = 
    from entrada in db.entradas
    group entrada.quant by entrada.idProduto into grupo
    select new { idProduto = grupo.Key, quant = grupo.Sum() };

var saidas = 
    from saida in db.saidas
    group saida.quant by saida.idProduto into grupo
    select new { idProduto = grupo.Key, quant = grupo.Sum() };

var estoque =
    from produto in db.produtos
    join entrada in entradas in produto.idProduto equals entrada.idProduto into leftEntradas
    from entrada in leftEntradas.DefaultIfEmpty()
    join saida in saidas in produto.idProduto equals saida.idProduto into leftSaidas
    from saida in leftSaidas.DefaultIfEmpty()
    select new estoqueAtual {
        produto = produto.idProduto,
        saldo = (entrada?.quant ?? 0) + (saida?.quant ?? 0)
    };
  • Can you explain this line: group entrada.quant by entrada.idProduto into grupo ?

Browser other questions tagged

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