I have this table :
Con   Fecha           Rid       Pdv   Pla   Descripcion       Total Quantity
----------------------------------------------------------------------------
1     2016-01-01    COMIDAS    FUEM   184   POZ ROJO           85      1
10    2016-01-01    DESAYUNOS  VTSI   184   POZ ROJO           85      4
100   2016-01-01    COMIDAS    VTSI   693   ENVASE 1 LT        10      1
101   2016-01-01    DESAYUNOS  REST   693   ENVASE 1 LT        10      2
102   2016-01-01    COMIDAS    VTSI   693   ENVASE 1 LT        10      1
103   2016-01-01    COMIDAS    REST   73    NOPAL/PIÑA VASO    34      6
104   2016-01-01    DESAYUNOS  REST   73    NOPAL/PIÑA VASO    34      1
105   2016-01-01    DESAYUNOS  REST   184   POZ ROJO           85      9
106   2016-01-01    COMIDAS    VTSI   693   ENVASE 1 LT        10      1
107   2016-01-01    CENAS      REST   184   POZ ROJO           85      2
108   2016-01-01    DESAYUNOS  REST   184   POZ ROJO           85      1
What I need is a Linq statement that sums all 'Quantity's' on each item that is unique based on the 'Pla' data that is my primary key, I want to know how much 'Quantity' each Distinct 'Pla' has and also sum the total of each distinct 'Pla' resulting in an output like this:
Con   Fecha           Rid       Pdv   Pla   Descripcion       Total Quantity
----------------------------------------------------------------------------
1     2016-01-01    COMIDAS    FUEM   184   POZ ROJO           1445    17
100   2016-01-01    COMIDAS    VTSI   693   ENVASE 1 LT         50     5
103   2016-01-01    COMIDAS    REST   73    NOPAL/PIÑA VASO     34     6
104   2016-01-01    DESAYUNOS  REST   73    NOPAL/PIÑA VASO     34     1
How can I get this output with a Linq statement? All I have until now is:
 foreach (var item in db.Pos.Select(l => l.Pla).Distinct())
 {
      //Do stuff
 }
                You need to use groupby
db.Pos.GroupBy(a=> a.Pla).Select(p=> new {Pla = p.Key, Quantity = p.Sum(q=>q.Quantity)});
GroupBy returns key as distinct so you will get distinct values for Pla with sum of their respective quantity
You can GroupBy the elements by Pla values and Sum the Total and Quantity values of each element in the group:
var plas = db.Pos.GroupBy(p => p.Pla).Select(g => new
{
    Pla = g.Key,
    Total = g.Sum(t => t.Total),
    Quantity = g.Sum(t => t.Quantity)
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With