可能的多个枚举的IEnumerable的?多个、IEnumerable

2023-09-07 14:01:22 作者:你融化在眉眼

这是为什么?我该如何解决?

why is that ? how can I fix it ?

推荐答案

没有什么可以在这里解决。 任何()将遍历枚举,但停止的第一个元素(在之后它返回true)之后。

There is nothing to fix here. Any() will iterate the enumeration but stop after the first element (after which it returns true).

多个枚举主要是在两种情况下一个问题:

Multiple enumerations are mainly a problem in two cases:

性能:一般来说,你想避免多次重复,如果你 能,因为它比较慢。因为这并不适用于此处的任何()将 只是确认至少有一个元素,是你必需的检查。你也不能访问任何远程/外部资源,只是在内存中的序列。

Performance: Generally you want to avoid multiple iterations if you can, because it is slower. This does not apply here since Any() will just confirm there is at least one element and is a required check for you. Also you are not accessing any remote/external resources, just an in-memory sequence.

枚举无法遍历不止一次:如 接收项目从网络等 - 也在这里并不适用

Enumerations that cannot be iterated over more than once: E.g. receiving items from a network etc. - also does not apply here.

由于只需要遍历一旦你的非LINQ的版本可能的做到以下几点:

As a non Linq version that only needs to iterate once you could do the following:

bool foundAny= false;
bool isEqual = true;

if(f == null)
  throw new ArgumentException();

foreach(var check in f)
{
   foundAny = true;
   isEqual = isEqual && check(p,p2);
}

if(!foundAny)
  throw new ArgumentException();

return isEqual;

不过,如前所述,在你的情况下,它不会有所作为,我会用这是更具可读性,你的版本去。

But, as noted, in your case it does not make a difference, and I would go with the version that is more readable to you.

 
精彩推荐
图片推荐