2

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;
  }
}
7
  • @FarhadJabiyev changing the i to j will keep repeat the value 1, 2, 3. I need the next one to be 4, 5, 6, etc. What the expectation is increment the i as shown in the sample above. And i can't declare variable i outside of the foreach loop. Commented Mar 8, 2015 at 7:43
  • 2
    You can increment i the same way as you already showing for j... Not sure what stops you from doing that... Commented Mar 8, 2015 at 7:45
  • Why can't you declare i outside the loops? If not, where did you declare it? Commented Mar 8, 2015 at 7:48
  • @item.Column1 + " " + i++; ? Commented Mar 8, 2015 at 7:49
  • Oh, missed the bit about not declaring i outside the loop. Although that just sounds wrong anyway. Commented Mar 8, 2015 at 7:50

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Given that the value of j isn't used, I'd probably have gone with for (int j = 0; j < 3; j++) as I prefer to have everything start at zero.
@Ceisc that's how the OP does it, so I've decided to leave it like this.
Yeah, I appreciate that is how the OP had it. My comment was more to suggest to them that it's more standard to do zero-based rather than a complaint that your answer didn't.
@Ceisc yeah, that's true, I will include the comment about it :)
Correct answer but it's woth noting that, in general, a View shouldn't be doing so much.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.