Ghasem
Ghasem

Reputation: 15623

Check if while loop is in first iteration in C#

How Can i check if it's the first iteration in my while loop in C#?

while (myCondition)
{
   if(first iteration)
     {
       //Do Somthin
     }

   //The rest of the codes
}

Upvotes: 1

Views: 6890

Answers (10)

sec feed
sec feed

Reputation: 1

Still learning, but this way came to me, have not used this before myself but I plan to test and possibly implement in my project:

int invCheck = 1;

if (invCheck > 0)
    {
        PathMainSouth(); //Link to somewhere
    }
    else
    {
        ContinueOtherPath(); //Link to a different path
    }

    static void PathMainSouth()
    {
        // do stuff here
    }

    static void ContinueOtherPath()
    {
        //do stuff
    }

Upvotes: -1

weston
weston

Reputation: 54811

You could move the do something out of the loop. Only guaranteed to do the exact same if the "Do Somthin" does not change myCondition. And myCondition test is pure, i.e. no side effects.

if (myCondition)
{
  //Do Somthin
}
while (myCondition)
{
   //The rest of the codes
}

Upvotes: 2

cbr
cbr

Reputation: 13660

You could make a bool outside the loop

 bool isFirst = true;
 while (myCondition)
 {
    if(isFirst)
      {
         isFirst = false;
        //Do Somthin
      }
    //The rest of the codes
 }

Upvotes: 1

Needham
Needham

Reputation: 467

I would recommend using counter variable for this, or a for loop.

E.G.

int i = 0;
while (myCondition)
{
   if(i == 0)
     {
       //Do Something
     }
i++;
   //The rest of the codes
}

Upvotes: 0

charpdevel0p3r
charpdevel0p3r

Reputation: 346

Try something like this:

bool firstIteration = true;
while (myCondition)
{
   if(firstIteration)
     {
       //Do Something
       firstIteration = false;
     }

   //The rest of the codes
}

Upvotes: 0

Tomas Smagurauskas
Tomas Smagurauskas

Reputation: 706

You can do that by workarounds, like:

boolean first = true;

    while (condition) 
    {
        if (first) {
            //your stuff
            first = false;
        }
    }

Upvotes: 0

Ken D
Ken D

Reputation: 5968

Define a boolean variable:

bool firstTime = true;

while (myCondition)
{
   if(firstTime)
     {
         //Do Somthin
         firstTime = false;
     }

   //The rest of the codes
}

Upvotes: 0

Simon
Simon

Reputation: 6152

Something like this?

var first=true;
while (myCondition)
{
   if(first)
     {
       //Do Somthin
     }

   //The rest of the codes
first=false
}

Upvotes: 0

Alex Anderson
Alex Anderson

Reputation: 860

bool firstIteration = true;
while (myCondition)
{
   if(firstIteration )
     {
       //Do Somthin
       firstIteration = false;
     }

   //The rest of the codes
}

Upvotes: 12

hwcverwe
hwcverwe

Reputation: 5367

use a counter:

int index = 0;
while(myCondition)
{
   if(index == 0) {
      // Do something
   }
   index++;
}

Upvotes: 1

Related Questions