可能的多个枚举的IEnumerable的? [英] Possible multiple enumeration of IEnumerable?

查看:244
本文介绍了可能的多个枚举的IEnumerable的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于可能的多个枚举的IEnumerable的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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