确定是否一个IEnumerable<>包含另一个IEnumberable中任何对象;> - .NET 3.5 [英] Determine if an IEnumerable<> contains any object of another IEnumberable<> - .Net 3.5

查看:111
本文介绍了确定是否一个IEnumerable<>包含另一个IEnumberable中任何对象;> - .NET 3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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; 实现不也实现<一个href="http://msdn.microsoft.com/en-us/library/92t2ye13.aspx"><$c$c>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()

      这篇关于确定是否一个IEnumerable&LT;&GT;包含另一个IEnumberable中任何对象;&GT; - .NET 3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆