c# - 在锯齿状数组中,如何在顶部添加新元素,即在第一个位置并删除最后一个元素
问题描述
我有一个锯齿状数组,
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 },
还有,如何从中删除最后一个元素?有没有办法实现我想要的?
解决方案
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.
推荐阅读
- c - 运算符如何在表达式优先级方面工作?
- marklogic - MarkLogic 数据中心安装和升级
- java - java8如何转换Future
到 CompleteableFuture - python-3.x - PermissionError: [Errno 13] Permission denied based on file size
- c# - 在 .net core web api 中实现基于用户的授权过滤器
- java - 带有 Java 的 WebDriver - 无法使用 Webdriver 获取所有文本
- python - 实现 f 字符串时如何捕获 SyntaxError - 使用过时的 python 时
- scikit-learn - 为什么 ColumnTransformer 使用相同的代码但不同的 .csv 文件产生不同的输出?
- reactjs - 如何在没有状态的情况下实现 TextInput [React-native]
- c# - WPF将用户控件属性绑定到主窗口