vincentsty
vincentsty

Reputation: 3221

Increment i inside for loop of foreach loop

I need to produce an output as below. For each item in @ViewBag.Table, duplicate 3 times and then increment the value i by 1 for each foreach iteration

eg: Values return by @ViewBag.Table { "Test", "AA", "Hello" }
Output:

Test   1
Test   2
Test   3
AA     4
AA     5
AA     6
Hello  7
Hello  8
Hello  9

How could this be done?

@foreach(var item in @ViewBag.Table)
{
  for (int j = 1; j <= 3; j++)
  {       
    @item.Column1 + " " + i;
  }
}

Upvotes: 2

Views: 5629

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

You can increment i anywhere inside the foreach loop, you can even do it on the same line where you assign it's value:

@{int i = 1;}
@foreach(var item in @ViewBag.Table)
{
  for (int j = 1; j <= 3; j++)
  {       
    @item.Column1 + " " + i++;
  }
}

PS. As Ceisc mentioned, a standard way to start begin the loop is to start it from 0.

Upvotes: 7

Related Questions