简体   繁体   English

如何从 c# 数组中的第 2 项切片元素?

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

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

You can use C# 8 indices and ranges feature您可以使用 C# 8 个索引和范围功能

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

It'll return all items from index 1 till the end of array and give you an expected slice {3, 2, 8, 7, 6, 1 } .它将返回从索引 1 到数组末尾的所有项目,并为您提供预期的切片{3, 2, 8, 7, 6, 1 } Again, it works only with C# 8 and .NET Core 3.x.同样,它仅适用于 C# 8 和 .NET Core 3.x。

For earliest versions of C# you should do this by yourself, using Array.Copy for example or System.Linq对于 C# 的最早版本,您应该自己执行此操作,例如使用Array.CopySystem.Linq

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

If you are using C# 8, you can use Indices & Range .如果您使用的是 C# 8,则可以使用Indices & Range It goes something like this:它是这样的:

var newArray = oldArray[1..];  // Takes everything from index 1 until the end.

You can use Linq to skip the fist item and take the rest.您可以使用 Linq 跳过第一项并拿走 rest。 This will give you the sequence:这将为您提供序列:

arr.Skip(1);

Which you can convert to a new array like this:您可以将其转换为这样的新数组:

var new_arr = arr.Skip(1).ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM