Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sequence of integers in C#?

Tags:

c#

.net

sequence

f#

People also ask

What is an integer term in a sequence?

An integer sequence is a definable sequence relative to M if there exists some formula P(x) in the language of set theory, with one free variable and no parameters, which is true in M for that integer sequence and false in M for all other integer sequences.

What is sequence in C sharp?

The C# Sequence class is used to manage database fields of type sequence. As sequences are effectively vectors of values, they are accessed through iterators. Where the C type mco_seq_iterator_h is used in C applications, the C# class Sequence serves the equivalent role in C# applications.


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

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

MSDN page here.


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


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++;
    }
}

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)

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.


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;
        }
    }