Adrian
Adrian

Reputation: 346

how to increment object property name in a loop

in my list of objects i have few similar properties.

week1 week2 week3 week4 week5 ...

I would like to be able to display them in a table based on the selected number of weeks by the user.

My idea was to use the loop like below, but i can't add "i" to the @data.week#number

  @for (var i = 0; i < Model.numberOfWeeks; i++)
                        {
                      <td>@[email protected]</td>
                        }

Is there a way i can use the incrementation of "i" to add it to the object name ?

Upvotes: 0

Views: 1405

Answers (2)

DolceVita
DolceVita

Reputation: 2100

Why do you have properties as values? Anyhow, if you really need to iterate properties and output their values you can try to use reflection:

 <td>@(data.GetType().GetProperty("week" + i).GetValue(data, null))</td>

But this is a bad practice. I would strongly recommend to change your data object and a view model.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can't use variables to construct variable names. The names must remain static. If you really need that there is reflection, but that is not the best option.

Use a dictionary or list instead, so that @data.weeks[@i].name would work.

Upvotes: 2

Related Questions