确定是否一个IEnumerable<>包含另一个IEnumberable中任何对象;> - .NET 3.5对象、GT、IEnumerable、LT

2023-09-03 12:14:56 作者:是有多不舍.才会哭泣

我有2 的IEnumerable< INT>

IEnumerable<int> x;
IEnumerable<int> y;

这是确定是否y中任何int是present在x问题最好最佳方式 目前我使用:

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;

的列表是相对较轻,具有和不超过50个整数英寸×4 y中,如果,在考虑事项。

The lists are relatively light, with not more than 50 ints in x and 4 in y if that matters in the consideration.

推荐答案

这将是最快使用的 任何方法代替的 计数方法:

It would be fastest to use the Any method instead of the Count method:

return x.Intersect<int>(y).Any();

这假定 的IEnumerable&LT; INT&GT; 实现不也实现ICollection<int>.在这种情况下,计数(的情况下,其中的IEnumerable&LT; T&GT; 工具的ICollection&LT; T&GT ; )是一个O(N)操作,而任何是总是的一个O(1)操作。 (因为只检查了的单的元素)。然而,的行为计数是一个实现细节,你不应该依赖于这一点。

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.

我已经写了这个更深入在博客中这将详细介绍何时使用计数()任何()。总结:

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()