2016-08-14 123 views
0

我有这个疑问:选择相同的记录

_ctx.TestPackageReportDetails.GroupBy(i => new { i.Status, i.TestPackageId }) 
       .Select(m => new { pid = m.Key.TestPackageId, count = m.Count(i => i.Status == "Accept") }) 

该查询返回185项与每个人的计数:

enter image description here

但我需要的项目与数量count=5所以我有这个查询:

_ctx.TestPackageReportDetails.GroupBy(i => new { i.Status, i.TestPackageId }) 
        .Select(m => new { pid = m.Key.TestPackageId, count = m.Count(i => i.Status == "Accept") }).Select(i => i.count == 5).Count(); 

但是这个retu 186为什么? enter image description here

确实有我的代码有问题吗?

+0

下来投票评论请 –

回答

1

您需要过滤使用Where分组结果:

int count = 
      _ctx.TestPackageReportDetails.GroupBy(i => new { i.Status, i.TestPackageId }) 
           .Where(m => m.Count(i => i.Status == "Accept") == 5).Count(); 

当你需要筛选,您使用.Where而不是.Select。选择遍历所有元素的循环并返回一个新指定的表单(也许从复杂对象中选择一个属性,或者出于某种原因将int转换为字符串)。

但是,如果需要过滤,则使用.Where,并将条件作为参数传递。

+0

谢谢你的作品,请问为什么我的查询返回意想不到的结果? –

+0

@EhsanAkbar,因为您的查询中没有筛选。选择不过滤,它只是将每个元素投影到一个新的表单中。所以在你的查询中没有你说的地方:*我只需要count = 5的组* – user3185569

+0

那么为什么它返回了186? –

1

count=5在where子句

_ctx.TestPackageReportDetails.GroupBy(i => new { i.Status, i.TestPackageId }) 
          .Select(m => new { pid = m.Key.TestPackageId, count = m.Count(i => i.Status == "Accept") }) 
          .Where(i => i.count == 5) 
          .Count(); 
+0

您的查询有语法错误 –

+0

伯爵是不是在where子句 –

+0

@EhsanAkbar现在检查访问 – Mostafiz