131

F# has sequences that allows to create sequences:

seq { 0 .. 10 }

Create sequence of numbers from 0 to 10.

Is there something similar in C#?

Jodrell
  • 34,946
  • 5
  • 87
  • 124
Budda
  • 18,015
  • 33
  • 124
  • 206

9 Answers9

230

You can use Enumerable.Range(0, 10);. Example:

var seq = Enumerable.Range(0, 10);

MSDN page here.

alexn
  • 57,867
  • 14
  • 111
  • 145
  • 74
    Note: This creates a sequence starting at 0 with 10 items (ending at 9). If you want 0 *through* 10, the second parameter would be 11. And if you need an actual array and not `IEnumerable`, include a call `.ToArray()`. – Anthony Pegram Jan 03 '11 at 22:11
41
Enumerable.Range(0, 11);

Generates a sequence of integral numbers within a specified range.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx

Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
20

You could create a simple function. This would work for a more complicated sequence. Otherwise the Enumerable.Range should do.

IEnumerable<int> Sequence(int n1, int n2)
{
    while (n1 <= n2)
    {
        yield return  n1++;
    }
}
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • By "more complicated" do you mean just "where you have begin and end handy instead of the number of elements"? Otherwise I'm missing your meaning. – ruffin Jul 27 '20 at 13:21
  • 1
    I believe I was considering `OddSequence` `EvenSequence` or other custom ranges. `if (++n1 % 2 == 0) yield return n1`, for example. It's been a few days ;) – Josiah Ruddell Jul 27 '20 at 22:27
  • 1
    Ha, yeah, one or two days I suppose. Or a few thousand. ;^) – ruffin Jul 28 '20 at 02:19
11

Linq projection with the rarely used indexer overload (i):

(new int[11]).Select((o,i) => i)

I prefer this method for its flexibilty.

For example, if I want evens:

(new int[11]).Select((item,i) => i*2)

Or if I want 5 minute increments of an hour:

(new int[12]).Select((item,i) => i*5)

Or strings:

(new int[12]).Select((item,i) => "Minute:" + i*5)
b_levitt
  • 7,059
  • 2
  • 41
  • 56
2

In C# 8.0 you can use Indices and ranges

For example:

var seq = 0..2;
var array = new string[]
{
    "First",
    "Second",
    "Third",
};

foreach(var s in array[seq])
{
    System.Console.WriteLine(s);
}
// Output: First, Second

Or if you want create IEnumerable<int> then you can use extension:

public static IEnumerable<int> ToEnumerable(this Range range)
{
   for (var i = range.Start.Value; i < range.End.Value; i++)
   {
       yield return i;
   }
}
...
var seq = 0..2;

foreach (var s in seq.ToEnumerable())
{
   System.Console.WriteLine(s);
}
// Output: 0, 1

P.S. But be careful with 'indexes from end'. For example, ToEnumerable extension method is not working with var seq = ^2..^0.

Evgeniy Mironov
  • 777
  • 6
  • 22
1

My implementation:

    private static IEnumerable<int> Sequence(int start, int end)
    {
        switch (Math.Sign(end - start))
        {
            case -1:
                while (start >= end)
                {
                    yield return start--;
                }

                break;

            case 1:
                while (start <= end)
                {
                    yield return start++;
                }

                break;

            default:
                yield break;
        }
    }
Dicaste
  • 31
  • 5
0

Originally answered here.


If you want to enumerate a sequence of numbers (IEnumerable<int>) from 0 to a 10, then try

Enumerable.Range(0, ++10);

In explanation, to get a sequence of numbers from 0 to 10, you want the sequence to start at 0 (remembering that there are 11 numbers between 0 and 10, inclusive).


If you want an unlimited linear series, you could write a function like

IEnumerable<int> Series(int k = 0, int n = 1, int c = 1)
{
    while (true)
    {
        yield return k;
        k = (c * k) + n;
    }
}

which you could use like

var ZeroTo10 = Series().Take(11);

If you want a function you can call repeatedly to generate incrementing numbers, perhaps you want somthing like.

using System.Threading;

private static int orderNumber = 0;

int Seq()
{
    return Interlocked.Increment(ref orderNumber);
}

When you call Seq() it will return the next order number and increment the counter.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
0

I have these functions in my code

private static IEnumerable<int> FromZero(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 0; i < count; i++)
        {
            yield return i;
        }
    }

    private static IEnumerable<int> FromOne(this int count)
    {
        if (count <= 0)
            yield break;

        for (var i = 1; i <= count; i++)
        {
            yield return i;
        }
    }

This helps to reduce some for(i) code.

haiduong87
  • 316
  • 3
  • 14
0

In case you wish to also save the generated sequence in a variable:

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

IEnumerable<int> numbersToPrint = Enumerable.Range(1, 11);

This is implicit in other solutions shown above, but I am also explicitly including the needed namespaces for this to work as expected.

Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51