我有2个IEnumerable<int>
IEnumerable<int> x;
IEnumerable<int> y;
确定 y 中的任何 int 是否存在于 x 中的最佳方法是什么?
目前我正在使用:
return x.Intersect<int>(y).Count() > 0;
单独循环并测试每个元素会明显更快吗?
foreach (int i in x)
{
foreach (int j in y)
{
if (i == j) return true;
}
}
return false;
这些列表相对较少,x 中的整数不超过 50 个,y 中的整数不超过 4 个(如果这在考虑中很重要的话)。
最快的方法是使用Any method http://msdn.microsoft.com/en-us/library/system.linq.enumerable.any.aspx而不是Count method http://msdn.microsoft.com/en-us/library/bb357758.aspx:
return x.Intersect<int>(y).Any();
这假设IEnumerable<int> http://msdn.microsoft.com/en-us/library/9eekhta0.aspx实施并不同时实施ICollection<int> http://msdn.microsoft.com/en-us/library/92t2ye13.aspx。在这种情况下,Count
(在这种情况下IEnumerable<T>
实施ICollection<T>
) 是一个 O(N) 运算,而Any
is alwaysO(1) 操作。 (因为它只检查single元素)。然而,的行为Count
是一个实现细节,您不应该依赖它。
我已经写过更深入的文章在一篇博文中 http://www.caspershouse.com/post/Anything-Counts.aspx详细介绍了何时使用Count()
vs. Any()
。总之:
-
DO use
Enumerable.Any
检查序列中元素是否存在的扩展方法。
-
DO NOT use
Enumerable.Count
extension method in comparisons against zero, as the following are semantically equivalent:
sequence.Count() == 0
!sequence.Any()
-
DO NOT use the
Enumerable.Count
extension method in comparisons against the “not zero” condition, as the following are semantically equivalent:
sequence.Count != 0
sequence.Any()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)