Anyname Donotcare
Anyname Donotcare

Reputation: 11393

How to increment a variable every n iterates according to some condition?

I have the following loop :

for (int i = 0; i < Main_dt.Rows.Count; i++)
{
}

Now i have one condition :

 if (dt.Rows.Count > 0)
  {
  }

What i wanna to do is :

if the condition is true then :

increment the variable j by 1 every two iterates,i mean like this :

0 0 1 1 2 2

if the condition is false then :

increment the variable j by 1 every three iterates,i mean like this :

0 0 0 1 1 1 2 2 2

Upvotes: 0

Views: 1540

Answers (3)

D Stanley
D Stanley

Reputation: 152521

long version

if (dt.Rows.Count > 0)
{
  if (i>0 && i%2 == 0)
     j++;
}
else
{
  if (i>0 && i%3 == 0)
     j++;
}

one-liner (not recommended as it takes some time to grok)

j += ( i>0 && i % (dt.Rows.Count > 0 ? 2 : 3) == 0) ? 1 : 0

Upvotes: 2

Richard Friend
Richard Friend

Reputation: 16018

int j = -1;
for (int i = 0; i < Main_dt.Rows.Count; i++) 
{
      j+= i% (dt.Rows.Count>0 ? 2 : 3) == 0 ? 1 : 0;
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500215

It sounds like you really want:

int scale = dt.Rows.Count > 0 ? 2 : 3;

for (int i = 0; i < Main_dt.Rows.Count; i++)
{
    int j = i / scale;
    ...
}

There may well be a better way of approaching this, but it's hard to know without more information about what you're trying to achieve.

Upvotes: 3

Related Questions