Reputation: 15623
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
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
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
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
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
Reputation: 346
Try something like this:
bool firstIteration = true;
while (myCondition)
{
if(firstIteration)
{
//Do Something
firstIteration = false;
}
//The rest of the codes
}
Upvotes: 0
Reputation: 706
You can do that by workarounds, like:
boolean first = true;
while (condition)
{
if (first) {
//your stuff
first = false;
}
}
Upvotes: 0
Reputation: 5968
Define a boolean variable:
bool firstTime = true;
while (myCondition)
{
if(firstTime)
{
//Do Somthin
firstTime = false;
}
//The rest of the codes
}
Upvotes: 0
Reputation: 6152
Something like this?
var first=true;
while (myCondition)
{
if(first)
{
//Do Somthin
}
//The rest of the codes
first=false
}
Upvotes: 0
Reputation: 860
bool firstIteration = true;
while (myCondition)
{
if(firstIteration )
{
//Do Somthin
firstIteration = false;
}
//The rest of the codes
}
Upvotes: 12
Reputation: 5367
use a counter:
int index = 0;
while(myCondition)
{
if(index == 0) {
// Do something
}
index++;
}
Upvotes: 1