2017-01-30 114 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);