dunika
dunika

Reputation: 220

Only display 10 items in foreach statement

I have the following razor code in my application. How can I have it so it only does 10 items from the model. So once it has done the following bit of code for 10 items in my model it stops

 @foreach (var item in this.Model.Leaderboard) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.userName)</td>
        <td> @Html.DisplayFor(modelItem => item.score)</td>   
    </tr>
}

Upvotes: 0

Views: 858

Answers (2)

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

You can use Take() method of Linq.

@foreach (var item in this.Model.Leaderboard.Take(10)) 
{
     <tr>
         <td>@Html.DisplayFor(modelItem => item.userName)</td>
         <td> @Html.DisplayFor(modelItem => item.score)</td>
     </tr>
}

As Henk Holterman suggested, If you don't need the whole collection, you should limit your collection where its created, not inside your view.

MSDN reference here.

Upvotes: 7

SLaks
SLaks

Reputation: 887509

You can use the LINQ .Take() method.

Upvotes: 2

Related Questions