First, sorry for a bad title, I don't really know what this is called.
I know that I can use context.Model.Where(a => a.Entity == "example").Count()
. But I want something more generic where I can get a count of how many rows have the same entry in one of the columns. A pic of what I mean:
My end result that I wanna get is a list of the count like: 3, 1 etc
You can use a GroupBy
statement for this to group by a value of your items, and then Select
the result you want from it:
var result = await db.Model
.GroupBy(x => x.Age)
.Select(g => new {
Age = g.Key,
Count = g.Count(),
})
.ToListAsync();
The result is a list of objects that have an Age
property with the age value, and a Count
property with the number of items that had that Age
value.
If you just want the counts, then you can just return those from the Select
expression directly:
var result = await db.Model
.GroupBy(x => x.Age)
.Select(g => g.Count())
.ToListAsync();
Note that this will obviously prevent you from saying what age an individual count is representing.