Blazor foreach loop and in

The foreach loop is commonly used to execute a block of codes for every item present in a collection as shown in the following Blazor .cshtml

@page "/"

<ul>
@foreach (var item in items)
{
  <li>
    @item
  </li>
}
</ul>

@functions {
  string[] items = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
}

The above will give you

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

A more useful example involving the use of class objects is shown below:

@page "/"

<ul>
    @foreach (var item in items)
    {
      <li>
        Name - @item.Name Id - @item.Id
        </li>
    }
    </ul>

@functions {
    public class Item
    {
        public Item(string name, string id)
        {
            Name = name;
            Id = id;
        }

        public string Name { get; set; }
        public string Id { get; set; }
    }

    Item[] items = new Item[] {
        new Item("Todo 1","1234"),
        new Item("Todo 2","1235")
  };

}
          

This will give you:

<ul>
<li>Name - Todo 1 Id - 1234</li> 
<li>Name - Todo 2 Id - 1235</li>
</ul>