HOWTO:计数从IEnumerable的&LT的项目; T>不反复?项目、IEnumerable、HOWTO、GT

2023-09-02 01:24:47 作者:看透不说透

private IEnumerable<string> Tables
{
    get
    {
        yield return "Foo";
        yield return "Bar";
    }
}

比方说,我想重复这些,写像处理#m的#N。

Let's say I want iterate on those and write something like processing #n of #m.

有没有一种方法可以让我找出m的值,而我的主要迭代之前迭代?

Is there a way I can find out the value of m without iterating before my main iteration?

我希望我自己清楚。

推荐答案

的IEnumerable 不支持这一点。这是由设计。 的IEnumerable 使用延迟计算,让你问之前你需要他们的元素。

IEnumerable doesn't support this. This is by design. IEnumerable uses lazy evaluation to get the elements you ask for just before you need them.

如果你想知道的项目数,而不遍历他们,你可以使用的IList&LT; T&GT; ,它有一个计数属性。

If you want to know the number of items without iterating over them you can use IList<T>, it has a Count property.