2012-07-25 134 views
1

可能重複:
Merging two arrays in .NET
How do I concatenate two arrays in C#?在.NET/C#2.0中合併兩個字符串數組?

我怎麼能合併兩個string[]變量?

例子:

string[] x = new string[] { "apple", "soup", "wizard" }; 
string[] y = new string[] { Q.displayName, Q.ID.toString(), "no more cheese" }; 

我想補充這兩個這樣的x的內容是:依次{"apple", "soup", "wizard",Q.displayName, Q.ID.toString(), "no more cheese"};。這可能嗎?如果結果必須進入一個新的字符串數組,這很好;我只想知道如何讓它發生。

+0

http://stackoverflow.com/questions/2788636/array-concatenation-in-c-sharp – Bert 2012-07-25 20:40:39

回答

2

既然你提到.NET 2.0和LINQ不可用,你在 「手動」 很堅持做:

string[] newArray = new string[x.Length + y.Length]; 
for(int i = 0; i<x.Length; i++) 
{ 
    newArray[i] = x[i]; 
} 

for(int i = 0; i<y.Length; i++) 
{ 
    newArray[i + x.Length] = y[i]; 
} 
3

你可以試試:

string[] a = new string[] { "A"}; 
string[] b = new string[] { "B"}; 

string[] concat = new string[a.Length + b.Length]; 

a.CopyTo(concat, 0); 
b.CopyTo(concat, a.Length); 

然後concat是你的連接數組。

+0

對不起夥計是2.0沒有這樣的東西.concat – DarthSheldon 2012-07-25 20:35:57

1

試試這個。

 string[] front = { "foo", "test","hello" , "world" }; 
    string[] back = { "apple", "soup", "wizard", "etc" }; 


    string[] combined = new string[front.Length + back.Length]; 
    Array.Copy(front, combined, front.Length); 
    Array.Copy(back, 0, combined, front.Length, back.Length);