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

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

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

我希望我讲清楚了。


当前回答

我的一个朋友有一系列的博客文章来说明为什么你不能这样做。他创建了一个返回IEnumerable的函数,每次迭代都会返回下一个质数,一直到ulong。MaxValue,下一项直到您请求它时才计算。一个简单的问题:返回了多少项?

以下是一些帖子,但它们有点长:

Beyond Loops(提供一个在其他帖子中使用的初始EnumerableUtility类) 迭代应用(初始实现) 疯狂的扩展方法:ToLazyList(性能优化)

其他回答

IEnumerable不迭代就不能计数。

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

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

这里有一个关于惰性求值和延迟执行的很好的讨论。基本上你必须物化这个列表才能得到这个值。

IEnumerable.Count()函数的结果可能是错误的。这是一个非常简单的测试样本:

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

namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      var test = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
      var result = test.Split(7);
      int cnt = 0;

      foreach (IEnumerable<int> chunk in result)
      {
        cnt = chunk.Count();
        Console.WriteLine(cnt);
      }
      cnt = result.Count();
      Console.WriteLine(cnt);
      Console.ReadLine();
    }
  }

  static class LinqExt
  {
    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkLength)
    {
      if (chunkLength <= 0)
        throw new ArgumentOutOfRangeException("chunkLength", "chunkLength must be greater than 0");

      IEnumerable<T> result = null;
      using (IEnumerator<T> enumerator = source.GetEnumerator())
      {
        while (enumerator.MoveNext())
        {
          result = GetChunk(enumerator, chunkLength);
          yield return result;
        }
      }
    }

    static IEnumerable<T> GetChunk<T>(IEnumerator<T> source, int chunkLength)
    {
      int x = chunkLength;
      do
        yield return source.Current;
      while (--x > 0 && source.MoveNext());
    }
  }
}

结果必须是(7,7,3,3),但实际结果是(7,7,3,17)

简化所有答案。

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

如果你有:

IEnumerable < >产品

然后:

声明:"using System.Linq;"

数:

.Count products.ToList ()

我使用这样的代码,如果我有字符串列表:

((IList<string>)Table).Count