这似乎有点奇怪,但很有可能被排除在外,以防止开发人员很容易写性能差的代码。 (如果要插入中间一个新的项目,你可能想要一个可调整大小的集合像List<T>
)到“插入”到一个固定大小的采集像Array
的唯一方法是将收集的内容复制到新收集,并把项目那里。显然,如果您执行大量插入操作,这不是最好的办法。
如果使用T[]
阵列的是你的控制之外,并且插入是必要的,复制自己的数组至少是最好你有,因为它可以节省你昂贵操作的代码:复制和插入这要求可能有很多元素被一个索引“转移”。 (您当前的解决方案复制long[]
的内容转换成一个List<long>
,然后插入一个项目成List<long>
,然后将复制List<long>
回到一个新的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
任何理由你正在使用一个列表? –
2010-12-09 20:36:04
它让我觉得奇怪的是来自PHP,但你有什么是我在C#中使用的东西# – Dinah 2010-12-09 20:36:40
没有什么内置到Array类,因为这是什么列表类是 –
2010-12-09 20:37:04