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


我还尝试将其修改为在分组依据中不包含FullRef。这样做是通过如下方式删除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)语句。

有人对如何解决有任何想法吗?
我想这就是问题所在。我能以某种方式避免分组吗?
我可能需要加入吗?

最佳答案

对于NHibernate,我不知道,但是使用Linq和Entity Framework可以得到您想要的:

var query2 = (
    from track in someDbSet
    select new FullReferrer
    {
          Customer = track.trackId
        , FullRefFalseCount = (from fullRefFalse in someDbSet.tracks
                               where fullRefFalse.IsSale == false
                               && fullRefFalse.trackId == track.trackId
                               select fullRefFalse).Count()
        , FullRefTrueCount = (from fullRefTrue in someDbSet.tracks
                              where fullRefTrue.IsSale == true
                              && fullRefTrue.trackId == track.trackId
                              select fullRefTrue).Count()
    }
).Distinct();

关于c# - LINQ查询中单个表上的多个计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16982783/

10-10 01:42