Thumbnail image

Accessing the Index of an Element When Using Foreach in C#

Hi, today I am here with an extremely simple article.

While writing foreach, you may need to access the index sometimes, although using for blocks makes more sense in such cases, it is possible to access the index while using foreach.

Normally I wouldn’t write about this topic, but it has been discussed a little on stackoverflow.

For this, it is necessary to have a little understanding of the using of lists.

If we need to explain with a simple example, let’s say you print the users to the table and you want to print the index.

foreach (var user in Model.Users)
{
    <tr>
        <td>
        @Html.DisplayFor(modelItem => user.Name)
        </td>

        <td>
        @Html.DisplayFor(modelItem => user.Surname)
        </td>
    <tr>
}

This is how I created a foreach with razor.

All you have to do is find the index of the element in your hand from Users and add one if we want it to start at once instead of zero. For this, we use IndexOf and add one.

    Model.Users.IndexOf(user)+1

Finally, our Foreach looks like this:

foreach (var user in Model.Users)
{
    <tr>
        <td>
        @(Model.Users.IndexOf(user)+1)
        </td>

        <td>
        @Html.DisplayFor(modelItem => user.Name)
        </td>
        
        <td>
        @Html.DisplayFor(modelItem => user.Surname)
        </td>
    <tr>
}

You can use this in any situation. With IndexOf, you can find the index of an element selected from a list.

Have a great day 👋