简体   繁体   中英

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>
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM