簡體   English   中英

如何使用 LINQ 計算與條件匹配的元素數量

[英]How to count the number of elements that match a condition with LINQ

我已經嘗試了很多事情,但對我來說最合乎邏輯的似乎是這個:

int divisor = AllMyControls.Take(p => p.IsActiveUserControlChecked).Count();

AllMyControlsUserControls的集合,我想知道有多少UserControlsIsActiveUserControlChecked屬性設置為 true。

我在 VS 中得到的是:

Cannot convert lambda expression to type 'int' because it is not a delegate type

我的表達有什么問題嗎?

int divisor = AllMyControls.Where(p => p.IsActiveUserControlChecked).Count()

或者干脆

int divisor = AllMyControls.Count(p => p.IsActiveUserControlChecked);

由於您是初學者,因此值得查看Enumerable文檔

為什么不直接使用Count == true語句也是非常多余的。

int divisor = AllMyControls.Count(p => p.IsActiveUserControlChecked);

此外,您的Take方法出現錯誤,因為它正在等待int 您需要從要獲取的集合的開頭指定連續元素的數量,不能放置 lambda 表達式。 為此,您需要使用TakeWhile 所以

int divisor = AllMyControls.TakeWhile(p => p.IsActiveUserControlChecked == true).Count();

本來是正確的,但不會像您期望的那樣工作; 一旦條件被打破,它就會停止。 因此,如果 AllMyControls 包含true, true, false, true ,帶有Count TakeWhile將返回 2 而不是您預期的 3。

不要親吻

int divisor = AllMyControls.Count(p => p.IsActiveUserControlChecked);

Take的參數需要一個int並且您正在傳遞一個委托/ lambda 表達式。 Take 旨在僅獲取元素的第一個count

您可以使用Count方法並傳入一個委托來計算符合其條件的元素。 這樣您只需迭代 IEnumerable 一次,而不是首先剔除不符合您的標准的那些,然后再次實際計算它們。

AllMyControls.Count(p => p.IsActiveUserControlChecked);

嘗試

int divisor = AllMyControls.Where(x => x.IsActiveUserControlChecked == true).Count();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM