Search code examples
c#sqllinq

Query with join, group by and count to linq


im doing this query on sql and it works, but how do i make it to Linq ?

select b.Name,a.idempresa,count(1) as cuenta from Descarga_XML_recepcion_V2 as a inner join EnterpriseSGE as b on a.idempresa = b.EnterpriseSGEId group by idempresa,b.name

this is what it should bring

name1 | 5041 |  583
name2 | 4031 |  1730
name3 | 5042 |  640
name4 | 4034 |  300
name5 | 6047 |  861
name6 | 5043 |  187
name7 | 4033 |  318

Solution

  • A straight forward translation of the SQL into LINQ yields:

    var ans = from a in Descarga_XML_recepcion_V2
              join b in EnterpriseSGE on a.idempresa equals b.EnterpriseSGEId
              group 1 by new { a.idempresa, b.name } into ingroup
              select new {
                ingroup.Key.idempresa,
                ingroup.Key.name,
                cuenta = ingroup.Count()
              };