Вопрос

I am using the following to dropdown displaying all countries in alphabetical order. It works fine. But my question is: Is the following loop ordering the country names in each iteration or it orders only once and then does a usual iteration?

<select id="dropDownID" name="NameID">
    <option value="NameID">Select Country...</option>
    @foreach (var item in Model.OrderBy(item => item.CountryName))
    {
        <option value="@item.NameID">@item.CountryName</option>
    }
</select>

Why I am sorting inside View and not in Controller I inherited this project from someone who used LinqToSQL for Model. The country table is in the O/R Designer that does not provide the choice for ordering the table data unless, I think, I modify the auto-generated code for this table but that would mean anytime the table is updated in SQL server I would need to update it in the O/R Designer by deleting and adding it again and hence update the auto-generated code manually as well. The other choice would be to create a SQL View in the SQL server and order the data there - and use that view in the LinqToSQL model. But I want to avoid creating an extra object for just ordering purposes. I think the better choice would be to avoid LinqToSQL altogether and order the data inside Controller.

Это было полезно?

Решение

It is called only once since foreach loop first calls GetEnumerator and only then starts iterating over it. Check this http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx However normally you should pass ordered model to view.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top