How to create a sequence of integers in C#?

后端 未结 8 878
野的像风
野的像风 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

    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 then you can use extension:

    public static IEnumerable 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.

提交回复
热议问题