How to slice elements from 2nd item in a c# array?

Sibtain Reza :

Given a 1D array,

double[] arr = { 4, 3, 2, 8, 7, 6, 1 };

I want to get values from 2nd index till last and want to store the array in a variable. Want to get something like this:

new_arr = {3, 2, 8, 7, 6, 1 }; //first element sliced
Pavel Anikhouski :

You can use C# 8 indices and ranges

double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr[1..];

It'll return all items from index 1 till end of array and give you an expected slice {3, 2, 8, 7, 6, 1 }. Again, it works only with C# 8 and .NET Core 3.x.

For earliest versions you should do this by yourself, using Array.Copy for example or System.Linq

double[] arr = { 4, 3, 2, 8, 7, 6, 1 };
var slice = arr.Skip(1).ToArray();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=410638&siteId=1