How do I clone a range of array elements to a new array?

前端 未结 25 1274
北海茫月
北海茫月 2020-11-22 16:07

I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a

25条回答
  •  攒了一身酷
    2020-11-22 16:51

    In C# 8, they've introduced a new Range and Index type, which can be used like this:

    int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Index i1 = 3;  // number 3 from beginning
    Index i2 = ^4; // number 4 from end
    var slice = a[i1..i2]; // { 3, 4, 5 }
    

    References:

    • https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0#ranges-and-indices
    • https://devblogs.microsoft.com/dotnet/building-c-8-0/

提交回复
热议问题