[英]Can I use the “Count” property on a Linq result?
我的代碼如下:
var result = from x in Values where x.Value > 5 select x;
然后,我想檢查一下:
if(result.Count > 0) { ... }
else if(result.Count == 1) { ... }
else { throw new Exception(...); }
但是,我得到的錯誤如下:
error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'int'
我可以不用結果寫一個foreach嗎?
使用result.Count()
。
更好的存儲它
int count = result.Count();
所以你不是多次迭代你的收藏。 另一個問題是
if(result.Count() > 0) { ... }
else if(result.Count() == 1) { ... } //would never execute
else { throw new Exception(...); }
檢查IEnumerable.Any()
擴展名,如果你想要if if執行,如果有任何項目。 使用該擴展意味着您不會像使用IEnumerable.Count()
那樣迭代集合。
LINQ使用擴展方法 ,因此您需要包括括號: result.Count()
但是LINQ有一個Any()
方法。 因此,如果你需要做的就是找出是否有超過0項,你可以使用Any ...
if (result.Any())
// then do whatever
...然后LINQ不必遍歷整個集合來獲取計數。
您可以在查詢上調用.ToList()以使其執行,然后您可以檢查.Count屬性的值。
正如已經說過的那樣,你需要一個Count()擴展方法。 但是,它需要迭代集合的所有元素來計算它們(通常情況下)。 如果元素的數量可能很大而您只需要檢查此數字是否等於1,則可以使用Take()方法:
else if (result.Take(2).Count() == 1)
它看起來不太好但會阻止對整個結果的迭代。
string[] name = new string[] { "Venu", "Bharath", "Sanjay", "Sarath", "Sandhiya", "Banu", "Gowtham", "Abdul Rahman", "Anamika", "Alex", "Austin", "Gilbert" };
var _lqResult = from nm in name where nm.StartsWith("A") select nm;
if (_lqResult.Count() > 1)
{
foreach (var n in _lqResult)
{
Console.WriteLine(n);
}
}
else {
Console.WriteLine("NO RESULT AVAILABLE");
}
只是result.count()將適用於LINQ結果,我在很多地方使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.