【问题标题】:How to get all the numbers from 2d array that pass the if condition into 1d array如何从二维数组中获取将if条件传递给一维数组的所有数字
【发布时间】:2016-10-13 02:42:27
【问题描述】:

对不起菜鸟问题:)。我有 2d 数组 3x3 填充随机数 (-5,5)

for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                {
                    dPole[i, j] = nc.Next(-10, 10);

我想要所有正数,然后将它们保存到一维数组中:

foreach (int j in dPole)
            {


                if (j > 0)
                {
                    Console.WriteLine(j);
                    for (int i = 0; i < sizeOf1dArray; i++)

                            jPole[i] = j;
                }
            }

Console.WriteLine(j)的输出-检查条件是否正确:

6
2
5
6
9
8

一维数组的输出:

8
8
8
8
8
8

只有最后一个数字被保存到数组中。为什么?谢谢。

【问题讨论】:

  • 因为您将值分配给数组的每个位置?这就是内部循环的作用。
  • 每次你在j &gt; 0处找到一个单个值,你就遍历整个 jPole数组并分配j值到每一个元素。在这里很难弄清楚如何为您提供帮助,因为 a)您已经抽象了太多问题,并且 b)不清楚为什么要编写该循环。
  • 请注意,您可以只使用jPole = dPole.Where(x =&gt; x &gt; 0).ToArray();(如果您不需要WriteLine()
  • 另外,如果您可以创建minimal reproducible example 并清楚地解释您在做什么,这会有所帮助。例如。您的叙述说数字在(-5,5) 之间,然后您立即向我们展示了一些代码(当我们不知道nc 是什么时)似乎产生的值(给定后面的示例/代码)可能超过5。
  • @LasseV.Karlsen 感谢您的回答。不过我不太明白。我知道内部循环正在为一维数组的每个位置赋值。我不知道的是如何分配所有数字,而不仅仅是最后一个。正确的代码应该是什么样的?

标签: c# arrays if-statement multidimensional-array conditional-statements


【解决方案1】:
   for (int i = 0; i < sizeOf1dArray; i++)

         jPole[i] = j;

因为在这个循环动作最后 j 值为 8 并且这个循环每次都用 j 值填充所有 jPole 数组,这意味着它首先用 6 填充所有,而不是在整个数组中放置 2,然后是 5......最后它用 8 填充它。

尝试类似的方法

int i = 0;
foreach (int j in dPole)
        {


            if (j > 0)
            {
                Console.WriteLine(j);
                jPole[i] = j;
                i++;
            }
        }

【讨论】:

    【解决方案2】:

    另一种方法是使用Cast&lt;int&gt; 来展平数组并使用Where 进行过滤。

    int[,] dPole = new int[,] { { 3, -5, 0 }, { -3, 3, 2 }, { -2, 1, 1 } };
    int[] jPole = dPole.Cast<int>().Where(i => i > 0).ToArray();
    // jPole is now { 3, 3, 2, 1, 1 };
    

    【讨论】:

      猜你喜欢
      • 2015-08-23
      • 1970-01-01
      • 2013-07-07
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多