How to create a sequence of integers in C#?

后端 未结 8 855
野的像风
野的像风 2020-11-30 02:32

F# has sequences that allows to create sequences:

seq { 0 .. 10 }

Create sequence of numbers from 0 to 10.

Is there someth

相关标签:
8条回答
  • 2020-11-30 03:34

    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)
    
    0 讨论(0)
  • 2020-11-30 03:34

    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.

    0 讨论(0)
提交回复
热议问题