Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count in lambda expression

Tags:

lambda

linq

I am trying to run a query where I get the name of locations and the number of items in that location. So if i have a program that contains 3 locations I want to know how many programs are in that location..I need to use this with a lambda expression or linq to entities.

return Repository.Find(x => x.Location.Name.Count())...clearly missing something here.

we'll just assume I have a Program entity with ProgramID, ProgramName, LocationName...need to know how many programs are in at a location

like image 280
gevjen Avatar asked Oct 25 '10 20:10

gevjen


2 Answers

You can do it like this:

return repository.Count(x => x.Location == "SomeLocation");
like image 57
Klaus Byskov Pedersen Avatar answered Nov 07 '22 00:11

Klaus Byskov Pedersen


Do you want to know the counts for all locations at once?

var locCounts = Repository.GroupBy(prog => prog.Location.Name).ToLookup(g => g.key, g => g.Count());
like image 5
Matt Ellen Avatar answered Nov 07 '22 01:11

Matt Ellen