Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Order by in foreach

Tags:

c#

asp.net-mvc

I'm new to MVC C#.

Here is a ready and working code (the part of the working code).

@foreach (var item in Model)
{            
    <div style="height: 200px; ">
        @Html.Raw(@item.Description)
    </div>
}

The problem is the Description is not displayed on the page in the proper order is. So, the order of <div>s should be slightly different.

How to modify the code so it works properly?

The order of the Description field should be ordered by Order column.

like image 874
Haradzieniec Avatar asked Feb 06 '14 09:02

Haradzieniec


3 Answers

Use OrderBy extension method on IEnumerable in System.Linq namespace

@foreach (var item in Model.OrderBy(i => i.Order))
{            
    <div style="height: 200px; ">
        @Html.Raw(@item.Description)
    </div>
}
like image 151
Guillaume Avatar answered Oct 14 '22 09:10

Guillaume


You can use the Linq OrderBy extension method

@foreach (var item in Model.OrderBy(i => i.Order))
{
}
like image 35
Liath Avatar answered Oct 14 '22 10:10

Liath


Directly use orderby

@foreach (var item in Model.OrderBy(i => i.Order))
{            
    <div style="height: 200px; ">
        @Html.Raw(@item.Description)
    </div>
}
like image 21
Vinay Pratap Singh Bhadauria Avatar answered Oct 14 '22 09:10

Vinay Pratap Singh Bhadauria