0

i wrote this code to show list of items it works fine but i want to check the value of trainer_id for the last row in foreach to create button based on this value but i dont know how

        @foreach (var item in Model.model2)
    {
<tr>


    <td>
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.who_reply)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Status)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Details)

    </td>




    @if (Convert.ToInt16(@Session["userID"]) == item.trainer_id)
    {
        <td>

            <input class="editreply"  id="editreply" type="button" value="edit" data-reply="@item.Details" data-reply_id="@item.Reply_Id" />

            @*@Html.ActionLink("Edit", "Edit", new { id = Model.model1. })*@

        </td>
    }

thanks for your assistance

Ahmed
  • 11
  • 3
  • Does this answer your question? [Foreach loop, determine which is the last iteration of the loop](https://stackoverflow.com/questions/7476174/foreach-loop-determine-which-is-the-last-iteration-of-the-loop) – Šimon Kocúrek May 15 '20 at 16:06
  • you can put the code outside ``foreach`` and get the last element from the list,like ``var item = Model.model2.Last()`` and test `if Convert.ToInt16(@Session["userID"])==item.trainer_id` – Mohammed Sajid May 15 '20 at 16:10

3 Answers3

1
@if(item == Model.model2.Last())
{
   ...
}
Jasper Kent
  • 3,360
  • 10
  • 19
  • 3
    Only works as long as the last item is unique in the list, whatever the definition of uniqueness is with that type (`T.Equals(object)`). – Blindy May 15 '20 at 16:07
  • Fair point @Blindy, but I think it's a fair assumption in this case. – Jasper Kent May 15 '20 at 18:29
0

Cleanest way is to iterate over the index:

@for(int idx = 0; idx < Model.model2.Length; ++idx)
{
    var item = Model.model2[idx];
    var isLast = idx == Model.model2.Length - 1;

    // ...
}

Alternatively, you can use foreach and use a function that also returns the index, like:

@foreach(var (item, idx) in Model.model2.Select((item, idx) => (item, idx)))
{
    var isLast = idx == Model.model2.Length - 1;

    // ...
}
Blindy
  • 55,135
  • 9
  • 81
  • 120
  • 1
    Not asked, but the absolute best answer is that in almost every case you shouldn't care, that's what CSS is for. The `:last-child` selector is made for this very reason. – Blindy May 15 '20 at 16:12
  • i think `isLast` will be always false, because `idx` will never equals `Model.model2.Length` in the first code. `++idx` executed after `var isLast = idx == Model.model2.Length;` – Mohammed Sajid May 15 '20 at 16:17
0
@if (Model.model2.IndexOf(item) == Model.model2.Count - 1)
{
 .
 .
 .
}
Mohammed Sajid
  • 4,572
  • 2
  • 12
  • 16
Ahmed
  • 11
  • 3