locked
How can I exit from the loop after showing four record RRS feed

  • Question

  • User-1355965324 posted

    Hi

    How can I exit from the loop after showing the 4  record only 

    @for (var i = 0; i < Model.consolidated_sales.Count(); i++)
            {
    
                <div style="display: inline-block;margin-right:15px">
                   
                     <div>@Model.consolidated_sales[i].Customer</div>
                     <div>@Model.consolidated_sales[i].QTY</div>
    }

    Thursday, July 16, 2020 8:23 AM

Answers

  • User475983607 posted

    How can I exit from the loop after showing the 4  record only 

    Write a basic "if" condition.  

    @for (var i = 0; i < 10; i++)
    {
        if (i == 4) return;
        <div>@i</div>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 10:11 AM
  • User-821857111 posted
    @for (var i = 0; i < 4; i++)
    {
    <div style="display: inline-block;margin-right:15px">
    <div>@Model.consolidated_sales[i].Customer</div>
    <div>@Model.consolidated_sales[i].QTY</div>
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 10:20 AM

All replies

  • User475983607 posted

    How can I exit from the loop after showing the 4  record only 

    Write a basic "if" condition.  

    @for (var i = 0; i < 10; i++)
    {
        if (i == 4) return;
        <div>@i</div>
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 10:11 AM
  • User-821857111 posted
    @for (var i = 0; i < 4; i++)
    {
    <div style="display: inline-block;margin-right:15px">
    <div>@Model.consolidated_sales[i].Customer</div>
    <div>@Model.consolidated_sales[i].QTY</div>
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 16, 2020 10:20 AM
  • User753101303 posted

    Hi,

    Or yet another option:

    var last=System.Math.Min(4,Model.consolidated_sales.Count());
    @for (var i = 0; i < last); i++)

    Or you could use var myList=Model.consolidated_sales.Take(4);  to select at most 4 rows (possibly maybe even in your original source query if not using at all extra rows), etc...

    Thursday, July 16, 2020 11:59 AM