我有一张包含TeamName
和CurrentStatus
字段的表格。我正在制作一个linq查询来获取每个团队以及每个状态记录的数量:
var teamStatusCounts = models.GroupBy(x => new { x.CurrentStatus, x.TeamName })
.Select(g => new { g.Key, Count = g.Count() });
此查询的结果返回除count为0之外的所有计数。我需要获取没有特定团队记录和特定状态(其中count = 0)的行。
答案 0 :(得分:2)
您可以为您期望的团队名称和状态设置单独的集合,并将缺少的集合添加到结果集
//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);
答案 1 :(得分:0)
我会首先选择球队名称和状态:
var teams = models.Select(x => x.TeamName).Distinct().ToList();
var status = models.Select(x => x.CurrentStatus).Distinct().ToList();
如果您已经知道列表条目,可以跳过此步骤。
然后,您可以为每个团队选择,每个州都可以选择模型数量:
var teamStatusCounts = teams.SelectMany(team => states.Select(state =>
new
{
TeamName = team,
CurrentStatus = state,
Count = models.Count(model =>
model.TeamName == team && model.CurrentStatus == state)
}));