I wanted to use a nested for loop in a razor file, and use the indexes of these for loops to determine which picture to show. My code looked like this:
@for (int i = 1; i < 6; i++)
{
<MudItem>
@for (int j = 1; j < 6; j++)
{
stoel = GereserveerdeStoelen.Where(s => s.XPositionChair == i && s.YPositionChair == j).SingleOrDefault();
@if (stoel is null)
{
<MudImage Width="40" Src="images/chair.png" Alt="chair" Class="d-flex align-center justify-center py-8" />
}
else
{
<MudImage Width="40" Src="images/chair_not.png" Alt="chair" Class="d-flex align-center justify-center py-8" />
}
}
</MudItem>
}
Sadly this did not seem to work. The value of i seemed to always be 6. I could not find the problem for this exact situation, but found a similar problem with lambdas, and the solution for that worked for me too. I assign the index to a local variable, and then use that local variable.
My new code looks like this:
@for (int i = 1; i < 6; i++)
{
int local = i;
<MudItem>
@for (int j = 1; j < 6; j++)
{
stoel = GereserveerdeStoelen.Where(s => s.XPositionChair == local && s.YPositionChair == j).SingleOrDefault();
@if (stoel is null)
{
<MudImage Width="40" Src="images/chair.png" Alt="chair" Class="d-flex align-center justify-center py-8" />
}
else
{
<MudImage Width="40" Src="images/chair_not.png" Alt="chair" Class="d-flex align-center justify-center py-8" />
}
}
</MudItem>
}
However, I don’t completely understand the issue, and why this solution works. Can someone provide an explanation?