Home > front end >  c# How do I iterate to the next item in a model within foreach loop?
c# How do I iterate to the next item in a model within foreach loop?

Time:10-13

Is there a way to move to the next item in the model within the foreach loop so that I can display 2 items per loop?

In theory, I would want it to display the Summary in the index 1 and then start the loop where it left off.

So loop 1 would display indexes 1 and 2, loop 2 would display indexes 3 and 4 and so on.

Code example:

@foreach (var item in Model)
{
    <div id="companyImage1" class='col-md-6 col-sm-12'>
    <img src='/images/Companies/@Html.DisplayFor(modelItem => item.ImageFilename)'/>
    </div>

    <div class='col-md-6 col-sm-12 companySummary1'>
        <header>@Html.DisplayFor(modelItem => item.CompanyName)</header>
        <p>@Html.DisplayFor(modelItem => item.Summary)</p>
    </div>


    <div class='companySummary2 col-md-6 col-sm-12'>
        <header>@Html.DisplayFor(modelItem => item.CompanyName)</header>
        <p>@Html.DisplayFor(modelItem => item.Summary)</p>
    </div>

    <div id="companyImage2" class='col-md-6 col-sm-12'>
        <img src="/images/Companies/@Html.DisplayFor(modelItem => item.ImageFilename)">
    </div>

}

What it looks like

What I want it to look like

CodePudding user response:

Probably simplest to change the foreach to a for and set incrementing to go by 2. Now you can find items in your collection by index, and index 1.

for (int i = 0; i < model.Count; i = 2)
{
    var item1 = model[i];
    var item2 = model[i 1];
    ...
}

Of course you have to make sure you don't go past the bounds of your collection, this will be caused by having uneven number of items, so you always need "pairs" of objects on your Model.

CodePudding user response:

Try to use the following code:

@for (var i = 0; i < Model.Count / 2; i  )
{
     <div id="companyImage1" class='col-md-6 col-sm-12'>
    <img src='/images/Companies/@Model[@(2*i)].ImageFilename'/>
    </div>

    <div class='col-md-6 col-sm-12 companySummary1'>
        <header>@Model[@(2*i)].CompanyName</header>
        <p>@Model[@(2*i)].Summary</p>
    </div>


    <div class='companySummary2 col-md-6 col-sm-12'>
        <header>@Model[@(2*i 1)].CompanyName</header>
        <p>@Model[@(2*i 1)].Summary</p>
    </div>

    <div id="companyImage2" class='col-md-6 col-sm-12'>
        <img src="/images/Companies/@Model[@(2*i 1)].ImageFilename">
    </div>

    </div>
}
@if (Model.Count%2 != 0)
{
    <div id="companyImage1" class='col-md-6 col-sm-12'>
    <img src='/images/Companies/@Model[@Model.Count].ImageFilename'/>
    </div>

    <div class='col-md-6 col-sm-12 companySummary1'>
        <header>@Model[@Model.Count].CompanyName</header>
        <p>@Model[@Model.Count].Summary</p>
    </div>

}
  • Related