我的代码如下:
var result = from x in Values where x.Value > 5 select x;
Run Code Online (Sandbox Code Playgroud)
然后,我想检查一下:
if(result.Count > 0) { ... }
else if(result.Count == 1) { ... }
else { throw new Exception(...); }
Run Code Online (Sandbox Code Playgroud)
但是,我得到的错误如下:
error CS0019: Operator '==' cannot be applied to operands of type 'method group' and 'int'
Run Code Online (Sandbox Code Playgroud)
我可以不用结果写一个foreach吗?
Yur*_*ich 17
使用result.Count().
更好的存储它
int count = result.Count();
Run Code Online (Sandbox Code Playgroud)
所以你不是多次迭代你的收藏.另一个问题是
if(result.Count() > 0) { ... }
else if(result.Count() == 1) { ... } //would never execute
else { throw new Exception(...); }
Run Code Online (Sandbox Code Playgroud)
检查IEnumerable.Any()扩展名,如果您打算在有任何项目的情况下执行if.使用该扩展意味着您不会像对待那样迭代集合IEnumerable.Count().
LINQ使用扩展方法,因此您需要包含括号:result.Count()
但是LINQ有一种Any()方法.因此,如果你需要做的就是找出是否有超过0项,你可以使用Any ...
if (result.Any())
// then do whatever
Run Code Online (Sandbox Code Playgroud)
...然后LINQ不必遍历整个集合来获取计数.