2010-12-09 79 views
0

比方说,我有一个名为long[]IDs阵列中的几个要素。C#:拼接阵列

什么是定索引处拼接成/插入一个新元素的最简单的方法?

现在我这样做,我不认为这是最佳的:

long[] IDs = ...; 

var IDsList = IDs.ToList(); 
IDsList.Insert(newId, indexToInsertAt); 

IDs = IDsList.ToArray(); 

没有什么内置到Array类?这让我觉得非常奇怪,来自[].splice()的JavaScript世界。

+6

任何理由你正在使用一个列表? – 2010-12-09 20:36:04

+0

它让我觉得奇怪的是来自PHP,但你有什么是我在C#中使用的东西# – Dinah 2010-12-09 20:36:40

+1

没有什么内置到Array类,因为这是什么列表类是 – 2010-12-09 20:37:04

回答

11

使用List<long>而非阵列,因为你需要做的插入。

6

这似乎有点奇怪,但很有可能被排除在外,以防止开发人员很容易写性能差的代码。 (如果要插入中间一个新的项目,你可能想要一个可调整大小的集合像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 
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;