【问题标题】:Copy single row from multidimensional array into new one dimensional array将单行从多维数组复制到新的一维数组
【发布时间】:2016-01-25 06:18:51
【问题描述】:

我想将多维数组中的特定行复制到一个新的一维数组中,该数组可以在我的代码中的其他地方使用。

输入:

多维数组[3,3]:

33 300 500,
56 354 516,
65 654 489,

需要的输出:

一维数组(第二行)

56 354 516

【问题讨论】:

  • 谢谢大家的回复。不得不道歉,我现在才意识到,我过度简化了问题,我应该更准确。我的多维数组包含“双”值。抱歉,对 c# 还是很陌生。您可以编辑问题以更好地适应问题。
  • 我认为包含 double、string 或 int 的数组并不重要。

标签: c# arrays multidimensional-array


【解决方案1】:

这是Buffer.BlockCopy 可能派上用场的情况:

int[,] original = new int[3, 3]
{
    { 33, 300, 500 },
    { 56, 354, 516 },
    { 65, 654, 489 }
};

int[] target = new int[3];
int rowIndex = 1; //get the row you want to extract your data from (start from 0)
int columnNo = original.GetLength(1); //get the number of column
Buffer.BlockCopy(original, rowIndex * columnNo * sizeof(int), target, 0, columnNo * sizeof(int));

你会得到你的target:

56, 354, 516

【讨论】:

    【解决方案2】:
    var source = new int[3, 3]
    {
        { 33, 300, 500 },
        { 56, 354, 516 },
        { 65, 654, 489 }
    };
    // initialize destination array with expected length
    var dest = new int[source.GetLength(1)];
    
    // define row number
    var rowNumber = 1;
    
    // copy elemements to destination array
    for (int i = 0; i < source.GetLength(1); i++)
    {
        dest[i] = (int) source.GetValue(rowNumber, i);
    }
    

    【讨论】:

    • 您好 Vadim,感谢您的帮助,您介意我编辑问题吗?我喜欢你的解决方案,但是我不能让它为“双”值工作。
    • @Crysthius 有什么问题?只需将所有int 行更改为doubleint[3, 3] -&gt; double[3, 3]new int[source.GetLength(1)]; -&gt; new double[source.GetLength(1)];(int) source.GetValue(rowNumber, i); -&gt; (double) source.GetValue(rowNumber, i);
    • 嗨 Vadim,感谢您的帮助,它成功了。亲切的问候
    【解决方案3】:

    应该是这样的:

            int[][] arrayComplex = {new[] {33, 300, 500},new []{56, 354, 516}, new []{65, 654, 489}};
            int[] arraySingle = new int[3];
            for (int i = 0; i < arrayComplex[1].Length; i++)
            {
                arraySingle[i] = arrayComplex[1][i];
            }
    
            foreach (var i in arraySingle)
            {
                Console.Write(i + "  ");
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多