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

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

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

我希望我讲清楚了。


当前回答

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

其他回答

我在一个方法中使用了这样的方法来检查传入的IEnumberable内容

if( iEnum.Cast<Object>().Count() > 0) 
{

}

在这样的方法中:

GetDataTable(IEnumberable iEnum)
{  
    if (iEnum != null && iEnum.Cast<Object>().Count() > 0) //--- proceed further

}

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

((IList<string>)Table).Count

简化所有答案。

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

如果你有:

IEnumerable < >产品

然后:

声明:"using System.Linq;"

数:

.Count products.ToList ()

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)

只是增加了一些额外的信息:

Count()扩展并不总是迭代。考虑Linq to Sql,其中计数将进入数据库,但不是返回所有行,而是发出Sql count()命令并返回结果。

此外,编译器(或运行时)足够聪明,如果有对象的Count()方法,它将调用该方法。所以这并不像其他回应者所说的那样,完全无知,总是为了计算元素而迭代。

在许多情况下,程序员只是检查if(可枚举的。Count != 0)使用Any()扩展方法,如if(enumerable.Any())使用linq的惰性求值要有效得多,因为一旦确定有任何元素,它就会短路。它的可读性也更强