比方说,我有一种long[]被称为IDs与阵列中的几个要素.
在给定索引处拼接/插入新元素的最简单方法是什么?
现在我正在这样做,我不认为这是最佳的:
long[] IDs = ...;
var IDsList = IDs.ToList();
IDsList.Insert(newId, indexToInsertAt);
IDs = IDsList.ToArray();
Run Code Online (Sandbox Code Playgroud)
Array班里没有内置的东西?!这让我非常奇怪,来自JavaScript的世界[].splice().
这可能看起来有点奇怪,但可能是为了防止开发人员过于轻松地编写性能不佳的代码.(如果你在中间插入一个新项目,你可能想要一个可调整大小的集合List<T>.)将"插入"固定大小的集合的唯一方法Array就是将集合的内容复制到一个新的集合中并放入项目那里.显然,如果您执行大量插入操作,这不是最佳选择.
如果T[]数组的使用超出了您的控制范围,并且需要插入,那么自己复制数组至少比您拥有的代码更好,因为它可以节省两个代价高昂的操作:复制和插入,这需要潜在的许多元素被一个指数"转移".(您当前的解决方案将内容复制long[]到a中List<long>,然后将项目插入其中List<long>,然后将其复制List<long> 回新的项目long[].)
在这种情况下(a的选择T[]是不可协商的),您可以考虑使用扩展方法来执行上面刚才描述的操作.这样,至少在需要此行为时,您可以使用可重用的代码片段.就像是:
public static class ArrayHelper
{
public static T[] Insert<T>(this T[] source, int index, T item)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (index < 0 || index > source.Length)
{
throw new ArgumentOutOfRangeException("index");
}
// Allocate a new array with enough space for one more item.
T[] result = new T[source.Length + 1];
// Copy all elements before the insertion point.
for (int i = 0; i < index; ++i)
{
result[i] = source[i];
}
// Insert the new value.
result[index] = item;
// Copy all elements after the insertion point.
for (int i = index; i < source.Length; ++i)
{
result[i + 1] = source[i];
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面是比你有什么现在,因为它仅需要执行一个完整的阵列的等效复制有效的多一个时间(不是两次),它也不需要任何中间元件的"移动".
用法:
int[] numbers = new int[] { 2, 3, 4 };
numbers = numbers.Insert(0, 1);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 2 3 4
| 归档时间: |
|
| 查看次数: |
6475 次 |
| 最近记录: |