假设我有一个名为long[]
的{{1}},其数组中包含一些元素。
在给定索引处拼接/插入新元素的最简单方法是什么?
现在我正在这样做,我认为这不是最佳选择:
IDs
long[] IDs = ...;
var IDsList = IDs.ToList();
IDsList.Insert(newId, indexToInsertAt);
IDs = IDsList.ToArray();
课程中没有任何内置内容?!这让我很奇怪,来自Array
的JavaScript世界。
答案 0 :(得分:11)
使用List<long>
代替数组,因为您需要进行插入。
答案 1 :(得分:6)
这可能看起来有点奇怪,但可能是为了防止开发人员过于轻松地编写性能不佳的代码。 (如果您在中间插入一个新项目,您可能需要一个可调整大小的集合,如List<T>
。)“插入”固定大小的集合(如Array
)的唯一方法是复制将集合的内容放入 new 集合中,并将项目放在那里。显然,如果您执行大量插入操作,这不是最佳选择。
如果使用T[]
数组不在你的控制之内,并且需要插入,那么自己复制数组至少比你拥有的代码更好,因为它可以节省你 2 昂贵的操作:复制和插入,这要求潜在的许多元素被一个索引“移动”。 (您当前的解决方案会将long[]
的内容复制到List<long>
,然后将项目插入List<long>
,然后复制List<long>
< em> back 成新的long[]
。)
在这种情况下(选择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;
}
}
请注意,上述内容比现在的效率要高得多,因为它只需要执行相当于完整数组副本一次时间(而不是两次),而且它也不需要要求任何中间“转移”元素。
用法:
int[] numbers = new int[] { 2, 3, 4 };
numbers = numbers.Insert(0, 1);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
输出:
1 2 3 4
答案 2 :(得分:1)
必须做类似的事情,这就是我想出的,类似于丹涛的:
T[] newArr = new T[oldArr.Length+1];
//copy first part of the array, starting with newArr[0] <- oldArr[0], up to the insertion point
System.Array.Copy(oldArr, 0, newArr, 0, insertIndex, insertIndex);
//insert new element
newArr[insertIndex] = spliceElem;
//copy the rest of the array, from newArr[insert+1] <- oldArr[insert] to the end
System.Array.Copy(oldArr, insertIndex, newArr, insertIndex + 1, oldArr.Length-insertIndex);
return newArr;
答案 3 :(得分:-1)