确定IEnumerable <T>是否包含另一个IEnumberable <T>的任何对象

Ada*_*dam 16 .net ienumerable

我有2个 IEnumerable<int>

IEnumerable<int> x;
IEnumerable<int> y;
Run Code Online (Sandbox Code Playgroud)

确定x中是否存在任何int的最佳方法是什么?
目前我正在使用:

return x.Intersect<int>(y).Count() > 0;
Run Code Online (Sandbox Code Playgroud)

是否可以明显更快地循环并单独测试每个?

foreach (int i in x)
{
    foreach (int j in y)
    {
        if (i == j) return true;
    }
}
return false;
Run Code Online (Sandbox Code Playgroud)

列表相对较轻,如果在考虑中重要,则x中不超过50个,y中不超过4个.

cas*_*One 27

这将是最快的使用Any方法,而不是Count方法:

return x.Intersect<int>(y).Any();
Run Code Online (Sandbox Code Playgroud)

这假设IEnumerable<int>实现也没有实现ICollection<int>.在这种情况下,Count(在的情况下IEnumerable<T>工具ICollection<T>)是O(N)操作,同时Any总是为O(1)的操作.(因为它只检查单个元素).但是,行为Count是一个实现细节,你不应该依赖它.

在博客文章中更深入地写了这篇文章,详细介绍了何时使用Count()vs Any()..综上所述:

  • 使用Enumerable.Any扩展方法检查序列中是否存在元素.
  • 请勿Enumerable.Count在与零进行比较时使用扩展方法,因为以下内容在语义上是等效的:
    • sequence.Count() == 0
    • !sequence.Any()
  • 请勿Enumerable.Count在与"非零"条件进行比较时使用扩展方法,因为以下内容在语义上是等效的:
    • sequence.Count != 0
    • sequence.Any()