在C#中弹出数组

rob*_*ntw 23 c# arrays

我在C#中有一个字符串数组,我想从数组中弹出顶部元素(即删除第一个元素,然后将所有其他元素向上移动一个).在C#中有一种简单的方法吗?我找不到Array.Pop方法.

我需要使用像ArrayList这样的东西吗?我的数组中项目的顺序很重要.

dri*_*iAn 33

使用列表,队列堆栈代替..

List<String>
Queue<String>
Stack<String>
Run Code Online (Sandbox Code Playgroud)

  • 虽然这个建议是公平的,但我不认为这回答了这个问题; 如何弹出数组中的第一个元素.至少也许你应该已经展示了如何使用List等. (11认同)
  • 我没有在这些类型的文档中看到Pop函数,除了Stack. (8认同)
  • 几年后,我偶然回到这里,现在我意识到我在这个具体问题上的表现优于@jon-skeet。我会把它刻在我的墓碑上。 (3认同)

Jon*_*eet 31

Queue<T>(先进先出)或Stack<T>(进去,先出)是你所追求的.

.NET中的数组是固定长度的 - 您无法从中删除元素或者确实向它们添加元素.您可以使用List<T>but 执行此操作,Queue<T>并且Stack<T>在需要队列/堆栈语义时更合适.


Pau*_*vre 12

来自MSDN:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class MSDNSample
    {
       static void Main()
       {
          string input = "a b c d";

          Stack<string> myStack = new Stack<string>(
             input.Split(new string[] { " " }, StringSplitOptions.None));

          // Remove the top element (will be d!)
          myStack.Pop();

          Queue<string> myQueue = new Queue<string>(

          input.Split(new string[] { " " }, StringSplitOptions.None));

          // Remove the first element (will be a!)
          myQueue.Dequeue();

       }
    }
}
Run Code Online (Sandbox Code Playgroud)

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/a924097e-3d72-439d-984a-b371cd10bcf4/


Art*_*aca 6

由于我们拥有linq,因此非常容易做到:

string[] array = ...;
array = array.Skip(1).ToArray();
Run Code Online (Sandbox Code Playgroud)