Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include count = 0 in linq results

Tags:

c#

count

linq

I have a table having TeamName and CurrentStatus fields. I am making a linq query to get for each team and for each status the count of records:

var teamStatusCounts = models.GroupBy(x => new { x.CurrentStatus, x.TeamName })
                             .Select(g => new { g.Key, Count = g.Count() });

The results of this query returns all the counts except where count is 0. I need to get the rows where there is no record for a specific team and a specific status (where count = 0).

like image 501
Hanady Avatar asked Oct 30 '22 22:10

Hanady


1 Answers

You could have a separate collection for team name and statuses you are expecting and add the missing ones to the result set

//assuming allTeamNamesAndStatuses is a cross joing of all 'CurrentStatus' and 'TeamNames'
var teamStatusCounts = models.GroupBy(x => new { x.CurrentStatus, x.TeamName })
                             .Select(g => new { g.Key, Count = g.Count() })
                             .ToList();

var missingTeamsAndStatuses = allTeamNamesAndStatuses
                   .Where(a=>
                      !teamStatusCounts.Any(b=>
                          b.Key.CurrentStatus == a.CurrentStatus 
                          && b.Key.TeamName == a.TeamName))
                   .Select(a=>new { 
                        Key = new {  a.CurrentStatus, a.TeamName  }, 
                        Count = 0 
                   });

teamStatusCounts.AddRange(emptyGroups);

I've created a fiddle demonstrating the answer as well

like image 96
konkked Avatar answered Nov 09 '22 10:11

konkked