我在LINQ查询的单个表上进行多个计数时遇到麻烦。我正在使用NHibernate,LINQ到NHibernate和C#。
查询是一个填充列表。我有一个表,该表具有一个称为FullRef的布尔值。我想执行一个LINQ查询,以给出每个TrackId上FullRef = false和FullRef = true的出现次数。 TrackId每次获得音轨时都会获得一个新行。Source==“ UserRef”。
在以下查询中,我获得了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()
};
有人对如何解决有任何想法吗?我敢肯定,.Where()子句会被忽略,并且“ group by”会把我搞砸。
如果我能以某种方式
group track by new { TrackId = track.TrackId, FullRefTrue = track.FullRef, FullRefFalse = !track.FullRef }"
它会工作。有什么办法可以做到这一点?
最佳答案
如果要按trackId进行结果,则应仅按trackId分组...
var query2 = query
.Where(m => m.Source == "UserRef")
.GroupBy(m => m.TrackId)
.Select(g => new FullReferrer {
Customer = g.Key,
FullRefFalseCount = g.Count(x => !x.FullRef),
FullRefTrueCount = g.Count(x => x.FullRef)
});