Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ with Lambda expression - Join, Group By, Sum and Count

Tags:

c#

sql

lambda

linq

How can I "translate" this SQL query to Linq Lambda Expression:

    SELECT  BN.DEUF, 
            BN.DESUPERINTENDENCIAREGIONAL,
            CR.SITUACAODIVIDA, 
            COUNT(CR.VLEFETIVAMENTELIBERADO), 
            SUM(CR.VLEFETIVAMENTELIBERADO)
   FROM BENEFICIARIO BN
   JOIN CREDITO CR ON BN.CDBENEFICIARIO = CR.CDBENEFICIARIO
   GROUP BY BN.DEUF,BN.DESUPERINTENDENCIAREGIONAL, CR.SITUACAODIVIDA
   ORDER BY BN.DEUF

Until now I have:

var itens = db.CREDITO
            .Join(db.BENEFICIARIO, cr => cr.CDBENEFICIARIO, bn => bn.CDBENEFICIARIO,
                                (cr, bn) => new { cr, bn })
            .GroupBy(cr => cr.VLEFETIVAMENTELIBERADO)
            .Select(g => new { VLTOTAL = g.Sum(x => x.VLEFETIVAMENTELIBERADO) })
            .ToList();
like image 555
Ian Campelo Avatar asked Nov 19 '15 12:11

Ian Campelo


1 Answers

You just don't do the same group by in your sql and your linq.

So... let's do it !

var itens = db.CREDITO
            .Join(db.BENEFICIARIO, cr => cr.CDBENEFICIARIO, bn => bn.CDBENEFICIARIO,(cr, bn) => new { cr, bn })
            .GroupBy(x=> new{x.bn.DEUF,x.bn.DESUPERINTENDENCIAREGIONAL, x.cr.SITUACAODIVIDA})
            .Select(g => new { 
                       g.Key.DEUF,
                       g.Key.DESUPERINTENDENCIAREGIONAL,
                       g.Key.SITUACAODIVIDA,
                       VLTOTAL = g.Sum(x => x.cr.VLEFETIVAMENTELIBERADO),
                       Count = g.Count() 
                       })
            .ToList();
like image 86
Raphaël Althaus Avatar answered Nov 14 '22 21:11

Raphaël Althaus