[英]What is the difference between these two LINQ statements?
我的代碼中有第一條語句,發現它沒有給出准確的計數,當正確答案為18時,它返回1。為嘗試調試問題,我在這里創建了第二條語句,結果計數為18。只是看不到兩者之間的區別。 似乎1st更加緊湊。
我當前正在背對背運行這兩個語句,並且我確定數據庫在這兩個之間沒有變化。
int count = (from s in surveysThisQuarter
where s.FacilityID == facility.LocationID
select s.Deficiencies).Count();
與
var tempSurveys = from s in surveysThisQuarter
where s.FacilityID == facility.LocationID
select s;
int count = 0;
foreach (Survey s in tempSurveys)
count += s.Deficiencies.Count();
在第一個查詢中,您要選擇一堆“缺陷集”並計算您擁有多少個整數 。 您想通過聲音來對它們求和:
int count = (from s in surveysThisQuarter
where s.FacilityID == facility.LocationID
select s.Deficiencies.Count()).Sum();
或(可能會生成更好的SQL,誰知道)
int count = (from s in surveysThisQuarter
where s.FacilityID == facility.LocationID
from x in s.Deficiencies
select x).Count();
那是因為第二個摘要對缺陷計數進行求和,而第一個摘要對缺陷進行計數。
這與您的第二個片段相同
int count = (from s in surveysThisQuarter
where s.FacilityID == facility.LocationID
select s.Deficiencies.Count()).Sum();
第一種形式是計算匹配的行數。 您應該改為使用Sum擴展方法。
第一個是在IEnumerable<Deficiencies>
(或任何類型的Deficiency)上返回一個Count
。 結果將與surveysThisQuarter.Count()
相同。 這是因為結果實際上是集合的集合。
第二個是計算所有缺陷-這可能是您想要的。
為了使第一個工作正常,您需要SelectMany
而不是Select
來展平集合。
我最好的猜測:
計數!=總和
您想要.Count
的累.Count
嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.