如何删除数组中的第一个元素? [重复]

时间:2021-01-30 21:21:38

This question already has an answer here:

这个问题在这里已有答案:

I have an array:

我有一个数组:

arr[0]="a"  
arr[1]="b"  
arr[2]="a"  

I want to remove only arr[0], and keep arr[1] and arr[2].
I was using:

我想只删除arr [0],并保持arr [1]和arr [2]。我用的是:

arr= arr.Where(w => w != arr[0]).ToArray();  

Since arr[0] and arr[2] have the same value ("a"), the result I'm getting is only arr[1].

由于arr [0]和arr [2]具有相同的值(“a”),因此我得到的结果只是arr [1]。

How can I return both arr[1] and arr[2], and only remove arr[0]?

如何返回arr [1]和arr [2],只删除arr [0]?

4 个解决方案

#1


70  

You can easily do that using Skip:

你可以使用Skip轻松完成:

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

This creates another array with new elements like in other answers. It's because you can't remove from or add elements to an array. Arrays have a fixed size.

这将创建另一个包含其他答案的新元素的数组。这是因为您无法从数组中删除或添加元素。数组具有固定大小。

#2


9  

You could try this:

你可以试试这个:

arr = arr.ToList().RemoveAt(0).ToArray();

We make a list based on the array we already have, we remove the element in the 0 position and cast the result to an array.

我们根据已有的数组创建一个列表,我们删除0位置的元素并将结果转换为数组。

or this:

或这个:

arr = arr.Where((item, index)=>index!=0).ToArray();

where we use the overloaded version of Where, which takes as an argument also the item's index. Please have a look here.

我们在哪里使用Where的重载版本,它也作为参数作为项目的索引。请看这里。

Update

更新

Another way, that is more elegant than the above, as D Stanley pointed out, is to use the Skip method:

另一种方式,就像D Stanley指出的那样,比上面更优雅的是使用Skip方法:

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

#3


2  

How About:

怎么样:

if (arr.Length > 0)
{
    arr = arr.ToList().RemoveAt(0).ToArray();
}
return arr;

#4


1  

Use second overload of Enumerable.Where:-

使用Enumerable.Where的第二个重载: -

arr = arr.Where((v,i) => i != 0).ToArray();

#1


70  

You can easily do that using Skip:

你可以使用Skip轻松完成:

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

This creates another array with new elements like in other answers. It's because you can't remove from or add elements to an array. Arrays have a fixed size.

这将创建另一个包含其他答案的新元素的数组。这是因为您无法从数组中删除或添加元素。数组具有固定大小。

#2


9  

You could try this:

你可以试试这个:

arr = arr.ToList().RemoveAt(0).ToArray();

We make a list based on the array we already have, we remove the element in the 0 position and cast the result to an array.

我们根据已有的数组创建一个列表,我们删除0位置的元素并将结果转换为数组。

or this:

或这个:

arr = arr.Where((item, index)=>index!=0).ToArray();

where we use the overloaded version of Where, which takes as an argument also the item's index. Please have a look here.

我们在哪里使用Where的重载版本,它也作为参数作为项目的索引。请看这里。

Update

更新

Another way, that is more elegant than the above, as D Stanley pointed out, is to use the Skip method:

另一种方式,就像D Stanley指出的那样,比上面更优雅的是使用Skip方法:

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

#3


2  

How About:

怎么样:

if (arr.Length > 0)
{
    arr = arr.ToList().RemoveAt(0).ToArray();
}
return arr;

#4


1  

Use second overload of Enumerable.Where:-

使用Enumerable.Where的第二个重载: -

arr = arr.Where((v,i) => i != 0).ToArray();