简体   繁体   English

将项添加到Jagged数组

[英]Add item to a Jagged array

I have already looked at some array topics but I am still stumped. 我已经看过一些数组主题,但我仍然感到难过。

I wish to add a new line to my jagged array - and am strugigng to get the syntax right.. 我希望在我的锯齿状数组中添加一个新行 - 并且为了使语法正确而受到严格限制。

        int[][] intJaggedArray = new int[7][];

        intJaggedArray[0] = new int[3] { 1, 1, 1 };
        intJaggedArray[1] = new int[3] { 2, 2, 2 };
        intJaggedArray[2] = new int[3] { 3, 3, 3 };
        intJaggedArray[3] = new int[3] { 4, 4, 4 };
        intJaggedArray[4] = new int[3] { 5, 5, 5 };
        intJaggedArray[5] = new int[3] { 6, 6, 6 };
        intJaggedArray[6] = new int[3] { 7, 7, 7 };

So now if i want to add 所以现在如果我想补充一下

        intJaggedArray[0] = new int[3] { 1, 1, 2 };

so the array ends up being as shown below how do I acheive it - thanks in advance - A noob from England. 因此阵列最终如下所示如何实现它 - 提前感谢 - 来自英格兰的菜鸟。 (And a big thanks in advance) (并提前表示非常感谢)

        intJaggedArray[0] = new int[3] { 1, 1, 1 };
        intJaggedArray[0] = new int[3] { 1, 1, 2 };
        intJaggedArray[1] = new int[3] { 2, 2, 2 };
        intJaggedArray[2] = new int[3] { 3, 3, 3 };
        intJaggedArray[3] = new int[3] { 4, 4, 4 };
        intJaggedArray[4] = new int[3] { 5, 5, 5 };
        intJaggedArray[5] = new int[3] { 6, 6, 6 };
        intJaggedArray[6] = new int[3] { 7, 7, 7 };

You might want to create a collection or a List<int[]> 您可能想要创建集合或List<int[]>

Then you could insert an item into it at a certain index. 然后你可以在某个索引处插入一个项目。

List<int[]> x = new List<int[]>();
x.Insert(3, new int[3] { 1, 2, 3 });

What do you want to do? 你想让我做什么? Insert a line between 0 and 1? 在0和1之间插入一条线? Or replace the existing line 0? 或者替换现有的0行?

Your line : 你的路线:

intJaggedArray[0] = new int[3] { 1, 1, 2 }; 

simply replaces the existing line 0. 只需替换现有的0行。

You can't insert a line in an array. 您不能在数组中插入行。 To do so, use a list instead: 为此,请使用列表:

List<int[]> myList = new List<int[]>();
myList.Add(new int[] {...});
myList.Add(new int[] {...});
myList.Add(new int[] {...});

...

myList.Insert(1, new int[] {...});

Or if you want to replace the existing line, then simply: 或者,如果要替换现有行,则只需:

If you want the initial list to be of a variable length, you cannot use an array. 如果希望初始列表具有可变长度,则不能使用数组。 Use a List instead. 请改用列表。

This should work: 这应该工作:

List<int[]> intJaggedList = new List<int[]>();
intJaggedList.Add( new int[3] { 1, 1, 1 } );
intJAggedList.Add( new int[3] { 2, 2, 2 } );
...

Then to insert your new array: 然后插入新数组:

intJaggedList.Insert( 1, new int[3] { 1, 1, 2 } );

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

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