LINQ组由多个计数组成

时间:2013-06-07 19:20:48

标签: c# linq nhibernate

我在LINQ查询中对单个表执行多次计数时遇到问题。我正在使用NHibernate,LINQ到NHibernate和C#。

查询是一个填充列表。我有一个表有一个名为FullRef的布尔值。我想做一个LINQ查询来计算每个TrackId上FullRef = false和FullRef = true的出现次数。每次获得track时,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 track by new { TrackId = track.TrackId, FullRefTrue = track.FullRef, FullRefFalse = !track.FullRef }" 

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

1 个答案:

答案 0 :(得分: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)
              });