question

jeba avatar image
4 Votes"
jeba asked ·

How can I enumerate an infinite sequence of integers in C#?

Is there a function in C# that returns an IEnumerator of the infinite sequence of integers [0, 1, 2, 3, 4, 5 ...]?

I'm currently doing

 Enumerable.Range (0, 1000000000).Select (x => x * x).TakeWhile (x => (x <= limit))

to enumerate all squares up to limit. I realize that this is effective, but if there's a built-in function that just counts up from 0, I would prefer to use it.

not-supported
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Three is no built-in function but you can easily define one.

 public static IEnumerable Integers(int start = 0)
 {
     while (true) yield return start++;
 }

It's possible to create one:

 Integers().Select(x => x * x).TakeWhile(x => x <= limit)

The integer variable can overflow but in your scenario might not be important.

If it is, you can change the code to throw an exception when an overflow happens.

 public static IEnumerable Integers(int start = 0)
 {
     while (true) checked { yield return start++;}
 }
2 Votes 2 ·
KennethTruyers-2307 avatar image
3 Votes"
KennethTruyers-2307 answered ·

Integers are not infinite, once you get to the end, it will overflow. So essentially the best you can do this:

 Enumerable.Range (0, int.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))

If you want larger ranges, you could choose different types:

 Enumerable.Range (0, long.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))
 Enumerable.Range (0, double.MaxValue).Select (x => x * x).TakeWhile (x => (x <= limit))

Note that since you're squaring the values, the above samples would overflow at some point (namely at the square root of MaxValue).

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

thomaslevesque avatar image
13 Votes"
thomaslevesque answered ·

Well, you can't really have an infinite sequence, since int only has 32 bits. But you can go up to int.MaxValue, using Enumerable.Range(0, int.MaxValue). There's no built-in function for this.

· 1 · Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

To get an infinite sequence, use BigInteger.
Be warned, you need a computer with infinite memory ;-)

1 Vote 1 ·