Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert sql with count to linq

Tags:

sql

linq

How can i convert this to linq?

select i.CatName,COUNT(*) as n_items
from ixcxs i
group by i.CatName

or lambda expression will be helpful

like image 480
Urah Avatar asked May 27 '26 07:05

Urah


2 Answers

You don't need to select first item from group to get CatName - use grouping key instead:

var query = from i in ixcxs
            group i by i.CatName into g
            select new {
               CatName = g.Key,
               n_items = g.Count()
            };

Same with methods syntax:

var query = ixcxs.GroupBy(i => i.CatName)
                 .Select(g => new { CatName = g.Key, n_items = g.Count() });
like image 60
Sergey Berezovskiy Avatar answered Jun 01 '26 10:06

Sergey Berezovskiy


Try

ixcxs.GroupBy(g => g.CatName)
    .Select(s => new 
    {
        CatName = s.Key, 
        n_items = s.Count() 
    });

same thing in query syntax:

from i in ixcxs
group i by i.CatName into g
select new 
{
    CatName = g.Key,
    n_items = g.Count()
}
like image 45
mnsr Avatar answered Jun 01 '26 09:06

mnsr