简体   繁体   English

Linq:确定序列中的项目数是否满足条件

[英]Linq: determine if the number of items in a sequence meets a condition

What I'm trying to do, exactly, is determine if there is only a single element in an IEnumerable and then act on that. 确切地说,我正在尝试确定IEnumerable是否只有单个元素,然后对其进行操作。 I could do a .Count() and a comparison against the result, but that is extremely inefficient. 可以做一个.Count()并与结果进行比较,但这效率极低。

Is there a more efficient way of asking an IEnumerable if the count of items it contains meets some threshold without using .Count() ? 是否有一种更有效的方式来查询IEnumerable而不包含.Count()的项目数是否满足某个阈值?

This would also take care of it: 这也可以解决:

if (seq.Skip(1).Any())
{
    // act on it
}
MyEnumerable.Take(2).Count() == 1 //to check if it has one element

ElementAtOrDefault(index) and comparing against null will work. ElementAtOrDefault(index)并与null比较将起作用。

if (seq.ElementAtOrDefault(2) == null) 
{
    // act on it
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM