0

Converting SQL to linq

SQL:

select COUNT(ID), N_CNIC 
from dbo.GENRegistrations 
group by N_CNIC

I tried this:

Attempt #1:

return GEDdb.GENRegistrations 
            .GroupBy(x => x.N_CNIC)
            .Select(x => x.Key)
            .Count();

Attempt #2:

return GEDdb.GENRegistrations
            .GroupBy(x => new { x.ID, x.N_CNIC })
            .Select(g => new { idd = g.Key.ID, cnidc = g.Key.N_CNIC })
            .ToList();

Attempt #3:

return GEDdb.GENRegistrations
            .SqlQuery("select COUNT(ID) from dbo.GENRegistrations group by N_CNIC")
            .ToList();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

Using regular query syntax:

var query =
    from x in GEDdb.GENRegistrations
    group 1 by x.N_CNIC into g
    select new
    {
        N_CNIC = g.Key,
        Count = g.Count(),
    };

Or using direct method calls:

var query = GEDdb.GENRegistrations
    .GroupBy(x => x.N_CNIC, _ => 1)
    .Select(g => new
    {
        N_CNIC = g.Key,
        Count = g.Count(),
    });
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272