C# foreach loop if item does not exists skip it

I have a loop like so:

@foreach(var elevation in inventory.Elevations)
{
     <td>@elevation.Title</td>
}

Now my inventory.Elevations could have either 3 or 4 items, never more or less.

And the title can either be "A", "B", "C" or "D". For an example one inventory.Elevations could have A, C & D but not B while another could have B, C, D but not A, while another could have A, B, D but not C. If that is the case I would like to display <td>&nbsp;</td> How would I accomplish this? I wouldnt even know what to try to accomplish this.

1 answer

  • answered 2021-02-19 05:20 Karan

    Define your all elevations in one list as var elevations = new List<string>() { "A", "B", "C", "D" };. Loop over each one and check in your inventory.Elevations. If found then get Title else &nbsp;. Complete code is like below.

    @{
        // Set all your elevations
        var elevations = new List<string>() { "A", "B", "C", "D" };
    }
    
    @foreach(var e in elevations)
    {
        <td>@(inventory.Elevations.FirstOrDefault(x => x.Title == e)?.Title ?? "&nbsp;")</td>
    }
    

    Or you can add ternary with condition elevations.Contains like below.

    @{
        // Set all your elevations
        var elevations = new List<string>() { "A", "B", "C", "D" };
    }
    
    @foreach(var elevation in inventory.Elevations)
    {
        <td>@(elevations.Contains(elevation.Title) ? elevation.Title : "&nbsp;")</td>
    }