【问题标题】:Append two or more array to a single master array将两个或更多阵列附加到单个主阵列
【发布时间】:2017-06-15 12:45:35
【问题描述】:

我是 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# 开始。

【问题讨论】:

  • d = {{1,2,3},{4,5,6},{7,8,9}}; 不是int[]
  • 应该d 是一个锯齿形 数组,即数组{{1,2,3},{4,5,6},{7,8,9}} 的数组或只是一个简单的1D 一个:{1, 2, 3, 4, 5, 6, 7, 8, 9}
  • @Roma 我不想一步到位
  • @Dmitry 它应该是锯齿状的,即数组数组,如code {{1,2,3},{4,5,6},{7,8,9}}

标签: c# arrays append


【解决方案1】:

好吧,如果你想要一个简单的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);

【讨论】:

  • 看起来最后一个 (List&lt;int[]&gt;) 是 OP 需要的。
  • 先生,它给了我一个错误error CS0246: The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?) 是在System 命名空间中吗?
  • 不,Listusing System.Collections.Generic; 命名空间中
【解决方案2】:

从您的代码看来,d 不是一维数组,但它似乎是一个锯齿状数组(和数组数组)。如果是这样,你可以这样写:

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

如果您想将所有数组连接到一个新的d,您可以使用:

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

【讨论】:

  • 先生,我不需要一个衬里想象它在一个 for 循环中,我想一个一个地添加它
  • 它是一维数组。
  • 那么使用第一个样本。
【解决方案3】:
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);

【讨论】:

    【解决方案4】:

    您可以使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2021-11-29
      相关资源
      最近更新 更多