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

假设我想要迭代这些并写一些类似于processing #n of #m的东西。

有没有一种方法可以让我在不进行主迭代的情况下求出m的值?

我希望我讲清楚了。


当前回答

简化所有答案。

IEnumerable没有Count函数或属性。为了得到这个,你可以存储count变量(例如,使用foreach)或使用Linq来获得count。

如果你有:

IEnumerable < >产品

然后:

声明:"using System.Linq;"

数:

.Count products.ToList ()

其他回答

你可以使用System.Linq。

using System;
using System.Collections.Generic;
using System.Linq;

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

    static void Main()
    {
        var x = new Test();
        Console.WriteLine(x.Tables.Count());
    }
}

你会得到结果'2'。

不,不一般。使用枚举对象的一点是,枚举中的实际对象集是不知道的(预先知道,甚至根本不知道)。

我使用IEnum<string>. toarray <string>()。长度,效果很好。

简化所有答案。

IEnumerable没有Count函数或属性。为了得到这个,你可以存储count变量(例如,使用foreach)或使用Linq来获得count。

如果你有:

IEnumerable < >产品

然后:

声明:"using System.Linq;"

数:

.Count products.ToList ()

我建议你打电话给ToList。是的,您正在提前进行枚举,但您仍然可以访问项目列表。