确定是否IEnumerable< T>包含另一个IEnumerable< T>的任何对象. [英] Determine if an IEnumerable<T> contains any object of another IEnumerable<T>
问题描述
我有2个IEnumerable<int>
IEnumerable<int> x;
IEnumerable<int> y;
确定x中是否存在y中的int的最佳最佳方法是什么?
目前我正在使用:
What is the best best way to determine if any int in y is present in the x?
Currently I'm using:
return x.Intersect<int>(y).Count() > 0;
循环遍历并分别进行测试会更快吗?
Would it be significantly faster to loop through and test each individually?
foreach (int i in x)
{
foreach (int j in y)
{
if (i == j) return true;
}
}
return false;
列表相对较轻,如果考虑的话,x的整数不超过50,y的整数不超过4.
The lists are relatively light, with not more than 50 ints in x and 4 in y if that matters in the consideration.
推荐答案
使用 Count
方法:
It would be fastest to use the Any
method instead of the Count
method:
return x.Intersect<int>(y).Any();
这假定 IEnumerable<int>
实现也不实现 ICollection<int>
.在这种情况下,Count
(在IEnumerable<T>
实现ICollection<T>
的情况下)是O(N)运算,而Any
总是 是O(1)运算. (因为它仅检查单个元素).但是,Count
的行为是一个实现细节,您不应依赖于此.
This assumes that the IEnumerable<int>
implementation doesn't also implement ICollection<int>
. In that case, Count
(in the case where IEnumerable<T>
implements ICollection<T>
) is an O(N) operation while Any
is always an O(1) operation. (as it only checks for a single element). However, the behavior of Count
is an implementation detail, and you shouldn't rely on that.
我已经在博客文章中对此问题进行了更深入的介绍 详细介绍了何时使用Count()
与Any()
.总结:
I've written about this more in-depth in a blog post that goes into detail about when to use Count()
vs. Any()
. In summary:
- DO 使用
Enumerable.Any
扩展方法来检查序列中元素的存在. - 请勿在与零的比较中使用
Enumerable.Count
扩展方法,因为以下在语义上是等效的:-
sequence.Count() == 0
-
!sequence.Any()
- DO use
Enumerable.Any
extension method to check for the existence of elements in the sequence. - DO NOT use
Enumerable.Count
extension method in comparisons against zero, as the following are semantically equivalent:sequence.Count() == 0
!sequence.Any()
-
sequence.Count != 0
-
sequence.Any()
sequence.Count != 0
sequence.Any()
这篇关于确定是否IEnumerable< T>包含另一个IEnumerable< T>的任何对象.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-