首页 > 解决方案 > 在锯齿状数组中,如何在顶部添加新元素,即在第一个位置并删除最后一个元素

问题描述

我有一个锯齿状数组,

    int[][] array = new int[][] {
        new int[] { 120, 120 },
        new int[] { 135, 120 },
        new int[] { 150, 120 },
        new int[] { 165, 120 },
        new int[] { 180, 120 }
    };

我想在其中添加新元素**在顶部/开头**,例如:

new int[] { 105, 120 },

还有,如何从中删除最后一个元素?有没有办法实现我想要的?

标签: c#arraysjagged-arrays

解决方案


You're going to want Array.Copy:

Array.Copy(array, 0, array, 1, array.Length - 1);

That will leave your array looking like:

int[][] array = new int[][] {
    new int[] { 120, 120 },
    new int[] { 120, 120 }
    new int[] { 135, 120 },
    new int[] { 150, 120 },
    new int[] { 165, 120 },
};

That is, we've duplicated the first element, and overwritten the last. We can then assign the first element:

array[0] = new int[] { 105, 120 };

You might prefer to use a List<int[]>:

List<int[]> list = new List<int[]>()
{
    new int[] { 120, 120 },
    new int[] { 135, 120 },
    new int[] { 150, 120 },
    new int[] { 165, 120 },
    new int[] { 180, 120 }
};

Then you can insert a new element at the beginning with:

list.Insert(0, new int[] { 105, 120 });

And remove the last element with:

list.RemoveAt(list.Length - 1);

A Queue<int[]> might be better still, as adding new items to the front will be cheaper.


推荐阅读