2d数组值的总和c#

时间:2016-06-23 13:34:04

标签: c# multidimensional-array visual-studio-2015

大家好我想创建一个检索方法来检索我的2d数组值的总和我已经构建了数组来填充用户输入但不知道如何总计所有数组值,因为我还在学习。

public int[,] ToysMade = new int[4, 5];
public String[] days = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

    public void UserInput()
    {
        String value;
        int numCount;


        //retrieveing length of ToysMade array dimensions if less than 0 repeat untill last dimension filled
        for (int i = 0; i < ToysMade.GetLength(0); i++)
        {
            for (int ii = 0; ii < ToysMade.GetLength(1); ii++)
            {
                //taking user input for array dimension 0 "first dimension" then increment it by 1 after input ready for next dimension "i + 1"
                value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value For " + days[ii] + " of week " + (i + 1).ToString() + " Enter Value");

                try
                {
                    //making sure for only int past through 
                    while (!(int.TryParse(value, out numCount)))
                    {
                        MessageBox.Show("Not a valid number, please try again.");
                        value = Microsoft.VisualBasic.Interaction.InputBox("Enter Value for " + days[i] + " of week " + (i + 1).ToString() + " Enter Value");
                    }
                    // taking values enterd from user and set next dimension for next input by incrementing it
                    ToysMade[i, ii] = numCount;

                }
                catch (Exception e)
                {
                    MessageBox.Show("Value enterd is not in a valid format");
                }
            }
        }
    }

3 个答案:

答案 0 :(得分:1)

我建议使用简单的 foreach 循环

  int total = 0;

  foreach (var item in ToysMade)
    total += item;

或嵌套循环,这是典型的2d数组

  int total = 0;

  for (int i = 0; i < ToysMade.GetLength(0); i++)
    for (int j = 0; j < ToysMade.GetLength(1); j++) 
      total += ToysMade[i, j];

答案 1 :(得分:0)

您可以通过IEnumerable<int>;

创建ToysMade来使用Linq
var total = ToysMade.Cast<int>().Sum();

答案 2 :(得分:0)

谢谢大家的精彩作品再次感谢谢谢

   public void Sum()
    {
        int total = 0;

        for(int i = 0;i < ToysMade.GetLength(0); i++)
        {
            for(int j = 0;j < ToysMade.GetLength(1); j++)
            {
                total += ToysMade[i, j];
            }
        }
        txtOutput.Text += "\r\nThe sum of products is: " + total.ToString();
    }