How to get count of number of rows where one of the columns entry is the same

c# entity-framework entity-framework-core

Question

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: enter image description here

My end result that I wanna get is a list of the count like: 3, 1 etc

1
1
9/17/2018 11:27:34 AM

Popular Answer

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.

Example result

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.

3
9/17/2018 12:08:34 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow