Ovidiu Ovidiu - 4 months ago 27
SQL Question

how to use group by LINQ

I need to show the company name with each number of employees(count of persons).

var result2 = (from c in NoOfEntities.listOfCompanies
join s in NoOfEntities.listOfStores on c.Id equals s.CompanyId
join p in NoOfEntities.listOfPersons on s.Id equals p.StoreId
group c by c.Name into newGroup
select newGroup );


I need to add the number of employees but i don`t have any idea how to add that counter.

thank you in advance

Answer
var result2 = (from c in NoOfEntities.listOfCompanies
                join s in NoOfEntities.listOfStores on c.Id equals s.CompanyId
                join p in NoOfEntities.listOfPersons on s.Id equals p.StoreId
                group p by c.Name into newGroup
                select new
                {
                    CompanyName = newGroup.Key,
                    NumberOfEmployees = newGroup.Count()
                });
Comments