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

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

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

我希望我讲清楚了。


当前回答

你可以使用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'。

其他回答

IEnumerable不支持这个。这是有意为之。IEnumerable使用惰性求值在需要元素之前获取它们。

如果你想知道项目的数量而不迭代它们,你可以使用ICollection<T>,它有一个Count属性。

除了你的直接问题(已经得到了否定的回答),如果你想在处理一个可枚举对象时报告进度,你可能想看看我的博客文章《在Linq查询期间报告进度》。

它让你这样做:

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (sender, e) =>
      {
          // pretend we have a collection of 
          // items to process
          var items = 1.To(1000);
          items
              .WithProgressReporting(progress => worker.ReportProgress(progress))
              .ForEach(item => Thread.Sleep(10)); // simulate some real work
      };

IEnumerable不迭代就不能计数。

在“正常”情况下,实现IEnumerable或IEnumerable<T>的类(如List<T>)可以通过返回List<T>来实现Count方法。数属性。然而,Count方法实际上不是在IEnumerable<T>或IEnumerable接口上定义的方法。(事实上,唯一一个是GetEnumerator。)这意味着不能为它提供特定于类的实现。

相反,Count是一个扩展方法,定义在静态类Enumerable上。这意味着可以在IEnumerable<T>派生类的任何实例上调用它,而不管该类的实现如何。但这也意味着它是在一个单独的地方实现的,在任何这些类的外部。这当然意味着它必须以一种完全独立于这些类内部的方式实现。计数的唯一方法是通过迭代。

它可能不会产生最好的性能,但你可以使用LINQ来计算IEnumerable中的元素:

public int GetEnumerableCount(IEnumerable Enumerable)
{
    return (from object Item in Enumerable
            select Item).Count();
}

你可以使用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'。