Cycling through the contents of an array

I use an int array to store a long list of integers. For each element of this array, I want to check if it is 1, if it is, that matters only to 1, otherwise if it is 2, do another material related to 2, and so on for each value stored in the array. I came up with the code below, but it does not work as expected, is there something I am missing? It happens that only the first value of the array is considered.

int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{ 
    if (variable1[i] == 1)
    {
        // arbitrary stuff
    }
    else if (variable1[i] ==2)
    {
        //arbitrary stuff
    }
}
+5
source share
4 answers

You are trying to do something that does not make sense. To see how this works, take a simple example: an array with values: 9, 4, 1.

If you try to run your code in this pattern array, you will receive an error message:

foreach (int i in variable1)
{ 
    if (variable1[i] == 1)   // the item i is 9.  
                             // But variable[i] means, get the value at position #9 in the array
                             // Since there are only 3 items in the array, you get an Out Of Range Exception
    {
        // arbitrary stuff
    }
{

:

foreach (int i in variable1)  // i will be 9, then 4, then 1)
{ 
    if (i == 1)   
    {
        // arbitrary stuff
    }
    // ... etc
}

, 0, 1 2, :

for (int i=0 ; i<=variable1.Length ; i++)   // i will be 0, 1, 2
                                            // variable[i] will be 9, 4, 1
{
    if (variable1[i] == 1) 
    { 
        // stuff
    }

    // ... etc
}
+4

i foreach , . , , , ( 0). , i, variable1[i].

, switch , BTW:

foreach (int i in variable1) {
    switch (i) {
        case 1:
            // arbitrary stuff
            break;
        case 2:
            // arbitrary stuff
            break;
    }
}

switch/case ; - , i, (i) switch, , switch , if - else.

.. foreach, - i. ,

  • , foreach
  • , for, .
+8

:

foreach (int i in variable1) {
    if (i == 1) {
    ....
+2

i , . i 1 2.

for, .

int[] variable1 = MyClass1.ArrayWorkings();
foreach (int i in variable1)
{ 
    switch(i)
    {
        case 1: 
            // arbitrary stuff
        break;
        case 2: 
            //arbitrary stuff
        break;
    }
}

. if-else.

0
source

All Articles