There is a best way to write this piece of code? (without validade if element at index i is not null)

I want to load 3 bootstrap cards with data per row and put it in 3 columns

Example and code:

 1. CARD 1 CARD 2 CARD 3
 2. CARD 4 CARD 5 CARD 6

@for (int i = 0; i < Model.Count()-1; i+=3)
{
    <div class="row top30">
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i))
        </div>
        @if (Model.ElementAtOrDefault(i + 1) != null) 
        {
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 1))
        </div>
        }
        @if (Model.ElementAtOrDefault(i + 2) != null)
        {
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 2))
        </div>
        }
    </div>
}

Related posts

Recent Viewed