2016-08-14 137 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