2017-01-30 117 views
0

我是新來的C#編程,我從python遷移。我想追加兩個或更多的數組(確切的數字是未知的,取決於數據庫條目)成一個單一的數組 像Python中的list.append方法。這裏我想做的代碼示例將兩個或多個數組添加到單個主數組中

int[] a = {1,2,3}; 
int[] b = {4,5,6}; 
int[] c = {7,8,9}; 
int[] d; 

我不想一次添加所有數組。我需要有點像這個

// I know this not correct 
d += a; 
d += b; 
d += c; 

這是最後的結果,我想

d = {{1,2,3},{4,5,6},{7,8,9}}; 

這將是太容易了你們卻對我只是用C#開始。

+0

'd = {{1,2,3},{4,5,6},{7,8,9}}; ''不是'int []' –

+0

應該是一個*鋸齒狀數組,即數組{{1,2,3},{4,5,6},{7,8,9}} '或者只是一個簡單的** 1D **:'{1,2,3,4,5,6,7,8,9}'? –

+0

@Roma我不想在一步之內 –

回答

2

好吧,如果你想要一個簡單的1D陣列,嘗試SelectMany

int[] a = { 1, 2, 3 }; 
    int[] b = { 4, 5, 6 }; 
    int[] c = { 7, 8, 9 }; 

    // d == {1, 2, 3, 4, 5, 6, 7, 8, 9} 
    int[] d = new[] { a, b, c } // initial jagged array 
    .SelectMany(item => item) // flattened 
    .ToArray();    // materialized as a array 

如果你想有一個鋸齒狀陣列(陣列陣列)的

// d == {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} 
    // notice the declaration - int[][] - array of arrays of int 
    int[][] d = new[] { a, b, c }; 

如果你想追加數組有條件地,不是一蹴而就的,array不是d的集合類型; List<int>List<int[]>或將有助於更好:

// 1d array emulation 
    List<int> d = new List<int>(); 
    ... 
    d.AddRange(a); 
    d.AddRange(b); 
    d.AddRange(c); 

或者

// jagged array emulation 
    List<int[]> d = new List<int[]>(); 
    ... 
    d.Add(a); //d.Add(a.ToArray()); if you want a copy of a 
    d.Add(b); 
    d.Add(c); 
+0

看起來最後那些('List ')是OP所需要的。 –

+0

先生,它給了我一個錯誤'錯誤CS0246:無法找到類型或命名空間名稱'列表'(你是否缺少一個使用指令或 程序集引用?)它是否在'System'命名空間中? –

+0

不,列表在'using System.Collections.Generic;'命名空間 –

0

從你的代碼看來,d不是一維數組,但它似乎是一個鋸齒形數組(和數組數組)。如果是這樣,你可以這樣寫:

int[][] d = new int[][] { a, b, c }; 

如果你不是想連接所有陣列到新d,你可以使用:

int[] d = a.Concat(b).Concat(c).ToArray(); 
+0

先生,我不需要一個班輪想象它在一個for循環和一個接一個我想添加它 –

+0

那麼第二個選項然後有什麼問題呢? –

+0

它是一維數組。 –

0
var z = new int[x.Length + y.Length]; 
x.CopyTo(z, 0); 
y.CopyTo(z, x.Length); 
0

您可以使用Array.Copy。它將一個數組中的一系列元素複製到另一個數組中。 Reference

int[] a = {1,2,3}; 
int[] b = {4,5,6}; 
int[] c = {7,8,9}; 

int[] combined = new int[a.Length + b.Length + c.Length]; 
Array.Copy(a, combined, a.Length); 
Array.Copy(b, 0, combined, a.Length, b.Length); 
Array.Copy(c, 0, combined, a.Length, b.Length, c.Length);