user3239140
user3239140

Reputation:

Loop Through Integer Array

What I am trying to do is loop through an integer array

int[] integerarray = { 1, 2, 3, 4 };
for (??????)
{
    // What do I do here?
}

Until I get to 3. I'm not sure how though.

Upvotes: 1

Views: 8105

Answers (5)

Gurunadh
Gurunadh

Reputation: 463

we can achieve this by using simple for each loop

foreach(int i in integerarray)
{
  if(i==3)
  {
   // do your stuf here;
    break;
  }
}

Upvotes: 4

jjrdk
jjrdk

Reputation: 1892

Use LINQ.

int[] integerarray = { 1, 2, 3, 4 };
for (var number = integerarray.TakeWhile(x => x != 3))
{
    // Do something
}

Upvotes: -2

Sachin
Sachin

Reputation: 40970

You can use linq TakeWhile method to get the elements from a sequence as long as a specified condition is true.

Here you want that return element untill we found 3 in the sequence so you can write this statement like this

var result = integerarray.TakeWhile(x => !x.Equals(3)).ToList();

result will contains the items which comes before 3

in your case result will have 1,2

Upvotes: 0

Neil N
Neil N

Reputation: 25268

One way to do a loop of a fixed number is a while loop.

int counter = 0;
while(counter < 3)
{
    tmp = integerArray[counter];
    ????
    counter++;
}

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

    int[] integerarray = { 1, 2, 3, 4 };
    for (int i=0;i<integerarray.Length;i++)
    {
        if(integerarray[i]==3)
            break;
        //Do something here 

    }

Upvotes: 2

Related Questions