开发者

Length of Yield Return

Is there a way to get the number of yield returns from within a function without keeping a counter variable? For ins开发者_运维知识库tance?

  IEnumerable<someobject> function
  {
      for loop
          yield return something

      int numberreturned = ....
  }


That would defeat the purpose of yield return.

Using yield return means you want to implement a generator (MSDN calls that an iterator block), i.e. an object that computes every value it returns on the fly. By definition, generators are potentially infinite, and therefore control might never leave your for loop.

Streams work the same way. To compute the length of a stream, you have to exhaust it, and you might never return from doing that. After all, the data could come from an infinite source (e.g. /dev/zero).


No. This is not possible without a counter -- there is no way to access the returned stream from within the function itself. (If it were possible, I wonder what sort of strange semantics/quirks it would entail?)

However, this is perfectly okay (if questionable) with a counter, even if the question does not desire such a response ;-) Remember that this form of construct is "magic" around closures invoked when the next item in the stream (iterator) is required -- that is, flow control leaves and re-enters at the yield return as required.

IEnumerable<someobject> Function
{
  int counter = 0;
  foreach (...) {
      counter++;
      yield return ...;
  }
  // after here we know count -- /assuming/ control gets here
  // 1) value can't be 'normally returned'
  // 2) and if the stream evaluation never exhausts the loop above
  //    then flow-control will never get here
}

Happy coding.


you could use the extension method count on the the IEnumerable<> that your function returns

function().Count()


You could use the IEnumerable.Count extension method!

I think that yield return is intended for the compiler to implicitly build a basic iterator using the statement that follows it.

If you want a more complex iterator then you might implement that in a more explicit manner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜