我在 LINQ 查询中对单个表进行多次计数时遇到问题。我正在使用 NHibernate、LINQ to NHibernate 和 C#。
查询是一个填充列表。我有一个表,它有一个名为 FullRef 的布尔值。我想做一个 LINQ 查询来计算每个 TrackId 上 FullRef = false 和 FullRef = true 的出现次数。每次获得 track.Source == "UserRef" 时,TrackId 都会获得一个新行。
在以下查询中,我得到了 FullRef = true 的正确数字计数(来自 FullRefTrueCount),但它在 FullRefFalseCount 上给出了一个未知的错误数字。
var query2 = from track in query
where track.Source == "UserRef"
group track by new { TrackId = track.TrackId, FullRef = track.FullRef } into d
select new FullReferrer
{
Customer = d.Key.TrackId,
FullRefFalseCount = d.Where(x => x.FullRef == false).Count(),
FullRefTrueCount = d.Where(x => x.FullRef == true).Count()
};
我还尝试将其修改为不包含 group by 中的 FullRef。这是通过像这样在 by 上删除 FullRef = track.FullRef 来完成的
var query2 = from track in query
where track.Source == "UserRef"
group track by new { TrackId = track.TrackId } into d
select new FullReferrer
{
Customer = d.Key.TrackId,
FullRefFalseCount = d.Where(x => x.FullRef == false).Count(),
FullRefTrueCount = d.Where(x => x.FullRef == true).Count()
};
现在它给了我 TrackId 的总数,忽略了我的 .Where(x => x.FullRef == true/false) 语句。
任何人都知道如何解决它?我想这是问题所在的“分组依据”。我可以以某种方式避免分组吗?我可能需要加入吗?