Search code examples
c#asp.net-mvcrazorasp.net-mvc-5razor-2

Alternative to foreach in C# Razor page


I need to output complex HTML containing an IEnumerable in a Razor page in an ASP.NET MVC 5 site.

I would like to use nested for loops to structure the HTML - however, this is not possible if all object output is enclosed in a foreach loop.

Rather than use a foreach loop, is there any way to do something like this which would get the next object in the sequence:

if (x = 1)
{
    for (var x=0; x<2; x++)
    {
        <div class="row">
            for (var n=0; n<4; n++)
            {
                <div class="a">
                    Model.GetNextObject.Name
                </div>
            }
        </div>
    }
}
else
{
    <div class="b">
        Model.GetNextObject.Name
    </div>
}

In many situations, this would allow for far more elegant code.

Is this possible?


Solution

  • yes, it is possible,

    1. Get the reference to Enumerator using GetEnumerator
    2. Call movenext method to move to next element

    Refer this stack overflow post Using IEnumerable with for loops

    var enumerator = getInt().GetEnumerator();
    while(enumerator.MoveNext())
    {
        var MyObject = enumerator.Current;
        Console.WriteLine(MyObject.Property);
    }