3

我在 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()
    };

任何人都知道如何解决它?我很确定 .Where() 子句被忽略了,而“group by”让我大吃一惊。如果我能以某种方式

group track by new { TrackId = track.TrackId, FullRefTrue = track.FullRef, FullRefFalse = !track.FullRef }" 

它会起作用的。有没有办法做到这一点?

4

1 回答 1

3

如果您希望通过 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)
              });
于 2013-06-07T19:27:32.040 回答