Rasmus Edvardsen
Rasmus Edvardsen

Reputation: 169

foreach loop where order needs to be specific

I am trying to go through an array of shipping methods, and then set them in a table as an option. The problem is that my shipping methods are scrambled, and we don't want to rearrange it in our database. That means I need to go through all elements, but in the order of the following shipmethodIDs: 11, 13, 12.

Following is the code snippet:

@foreach (var shippingMethod in availableShippingMethods)
{
    bool chosen = false;
    if (choosenShippingMethod != null)
    {
        if (choosenShippingMethod.Id == shippingMethod.Id)
        {
            chosen = true;
        }
    }
    else
    {
        chosen = counter == availableShippingMethods.Count();
    }
    <td>
        ... some html here ...
    </td>
}

Upvotes: 1

Views: 558

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157038

Create a column in your database table called sorting_order, sort on that column from your query or a view and you are done. Flexible, reusable, check.

Never rely on IDs never changing, or other weird logic. You can't maintain such software.

Upvotes: 3

Related Questions