如何使用 LINQ 计算与条件匹配的元素数量 [英] How to count the number of elements that match a condition with LINQ

查看:39
本文介绍了如何使用 LINQ 计算与条件匹配的元素数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多方法,但对我来说最合乎逻辑的似乎是这个:

I've tried a lot of things but the most logical one for me seems this one:

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

AllMyControlsUserControls 的集合,我想知道有多少 UserControlsIsActiveUserControlChecked属性设置为 true.

AllMyControls is a Collection of UserControls, what I want to know is how many UserControls have the IsActiveUserControlChecked property set to true.

我在 VS 中得到的是:

What I get in VS is:

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 文档

Since you are a beginner, it would be worthwhile to take a look at Enumerable documentation

这篇关于如何使用 LINQ 计算与条件匹配的元素数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆