高效的LINQ可枚举的“伯爵()== 1'测试 [英] Efficient Linq Enumerable's 'Count() == 1' test
本文介绍了高效的LINQ可枚举的“伯爵()== 1'测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与此类似问题转述,但对LINQ:
您可以使用可枚举< T>。任何()
来测试,如果枚举包含数据。但是,什么是要测试是否枚举包含单个值(即可枚举&所述; T> .Count之间()== 1
)的有效的方法(或不是单个值越大即可枚举< T> .Count之间的()→1
),无需使用昂贵的计数操作
解决方案? / DIV>
INT constrainedCount = yourSequence.Take(2).Count之间的();
//如果constrainedCount == 0则该序列是空
//如果constrainedCount == 1则序列包含单个元件
//如果constrainedCount == 2然后该序列有一个以上的元件
Similar to this question but rephrased for Linq:
You can use Enumerable<T>.Any()
to test if the enumerable contains data. But what's the efficient way to test if the enumerable contains a single value (i.e. Enumerable<T>.Count() == 1
) or greater than a single value (i.e. Enumerable<T>.Count() > 1
) without using an expensive count operation?
解决方案
int constrainedCount = yourSequence.Take(2).Count();
// if constrainedCount == 0 then the sequence is empty
// if constrainedCount == 1 then the sequence contains a single element
// if constrainedCount == 2 then the sequence has more than one element
这篇关于高效的LINQ可枚举的“伯爵()== 1'测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文