How to create array with sequence of integers in C

2019-01-10 19:40发布

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#?

6条回答
该账号已被封号
2楼-- · 2019-01-10 20:17

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)
查看更多
做个烂人
3楼-- · 2019-01-10 20:24

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

Enumerable.Range(0, ++end);

In explanation, to get a sequence of numbers from 0 to 1000, you want the sequence to start at 0 (remembering that there are 1001 numbers between 0 and 1000, 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 ZeroTo1000 = Series().Take(1001);

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.

查看更多
疯言疯语
4楼-- · 2019-01-10 20:26
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

查看更多
家丑人穷心不美
5楼-- · 2019-01-10 20:27

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++;
    }
}
查看更多
戒情不戒烟
6楼-- · 2019-01-10 20:31

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;
        }
    }
查看更多
Rolldiameter
7楼-- · 2019-01-10 20:38

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

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

MSDN page here.

查看更多
登录 后发表回答