如果没有找到记录,则linq groupby计数返回零。但我想要空列表

时间:2016-10-19 05:41:45

标签: c# linq

我有一个列表,我试图通过使用group by返回计数。以下是LINQ查询:

var data = from i in table
           where i.Date != null
           group i by new { 
              LineOfBusiness = i.LOB != null ? i.LOB.ReferenceName : string.Empty, 
              COE = i.COE != null ? i.COE.ReferenceName : string.Empty } 
              into g 
              select new
              {
                LineOfBusiness = g.Key.LineOfBusiness,
                COE = g.Key.COE,
                MTD = g.Count(a => a.Date >= startDate && a.Date <= endDate),
                YTD = g.Count(a => a.Date >= YTDStartDate && a.Date <= endDate)
              };

我的结果基于日期

LineOfBuiness  |    COE     | MTD  |  YTD
---------------+------------+------+-------
       A       |     X      |  0   |   0
       B       |     Y      |  0   |   0

如果MTD或YTD有一些价值没有问题但是如果MTD&amp;对于所有行,YTD为零,然后我想要null结果。我怎么能得到它?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

var data = from i in table
       where i.Date != null
       group i by new { 
          LineOfBusiness = I.LOB?.LOB.ReferenceName ?? string.Empty, 
          COE = i.COE?.ReferenceName : string.Empty } 
          into g 
          select new
          {
            LineOfBusiness = g.Key.LineOfBusiness,
            COE = g.Key.COE,
            MTD = g.Count(a => a.Date >= startDate && a.Date <= endDate),
            YTD = g.Count(a => a.Date >= YTDStartDate && a.Date <= endDate)
          };

data = data.All(x => x.MTD == 0 && x.YTD == 0) ? null : data;