2013-10-03 79 views
-4

我有命名爲items兩個String數組和items1 items陣列由1296個元素 items1陣列由 複製items1items 8個元件。我想這樣的事情,但它不工作,讓看看這個如何使用C#將字符串數組複製到另一個字符串數組?

items1.CopyTo(items, items1.Length -1); 
Array.Copy(items1, items, items1.Length-1); 
+0

什麼「不起作用」呢? – CodingIntrigue

+2

你想複製這些元素的位置?你希望'item'從'items1'有* first * 8個元素,或者它應該是* last * 8個元素?或者你想'物品'只包含8個元素? –

+0

哪個版本的.net框架 – TalentTuner

回答

1

這應該工作

Array.Resize(ref items, items.Length + items1.Length); 
Array.Copy(items1, 0, items, items.Length - items1.Length, items1.Length); 

如果您希望元素附加,而不是覆蓋嘗試以下

items = items.Concat(items1).ToArray(); 

順便說一句使用有意義的名稱,itemsitems1不使任何意義

1

使用LINQ的Concat的方法

items.Concat(items1) 

這將連接兩個數組在一起,並在項目的末尾添加items1,我希望你想要的項目只有這樣的數組。

+0

Concat不在那裏 – Anjali

+0

關心包含System.Linq命名空間 – TalentTuner

+0

我正在使用Linq命名空間。我的框架是.net3.5 – Anjali

0

它應該適合你:

var items = new string[]{"A"}; 
var items1 = new string[] { "B" }; 
var res = new List<string>(); 
res.AddRange(items); 
res.AddRange(items1); 
items = res.ToArray(); 

你的情況的主要問題是在運行時增加items數組的長度。如果您的物品陣列中有足夠的長度,則可以使用:

Array.Copy(items1, 0, items, items.Length, items1.Length); 
0

這是複製string Array的一個簡單示例。

 string[] SourceArray= { "A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S" }; 

     string[] DestArray= new string[8]; 
     Array.Copy(SourceArray, 11, DestArray, 0, 8); 

SourceArray =輸入陣列

11 =起始索引(從其中複製應在源陣列啓動)

DestArray =是您的陣列,其中所述元件具有要被複制

0 =目的地陣列的起始索引

8 =到陣列中的被複制elemets數

輸出:

{L,M,N,O,P,Q,R,S}

0

這應該做到這一點:

Array.Resize(ref items, items.Length + items1.Length); 
Array.Copy(items1, 0, items, items.Length-items1.Length, items1.Length); 

它調整目標數組的大小,items,足夠大,兩個陣列。 然後它將源數組items1複製到目標數組末尾新添加的空間。

相關問題