Connor McGill
Connor McGill

Reputation: 269

Ordering items from a model in a list C#

I'm new to MVC 4 and I'm trying to figure out how to order a list that is being created by reading in from a model.

Here is the model code:

public class Files
{
    [Key]
    public int File_id { get; set; }
    public string Original_file_name { get; set; }
    public string Current_file_name { get; set; }
    public string Description { get; set; }
    public string File_path { get; set; }
    public string File_type { get; set; }
    public string File_status { get; set; }
    public DateTime Expiry_date { get; set; }
    //public int Uploaded_by { get; set; }
    //public DateTime Uploaded_on { get; set; }
}

public class FilesContext : DbContext
{
    public DbSet<Files> Files { get; set; }
}

Here is the controller code that creates the list:

return View(db.Files.ToList());

Lastly the html that writes it to screen:

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Original_file_name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Current_file_name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.File_type)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.File_status)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Expiry_date)
    </td>
    <td>
        @Html.ActionLink("Details", "Details", new { id=item.File_id }) |
        <[email protected]("Test", "Test", new { id=item.File_id }) |-->
        @Html.ActionLink("Delete", "Delete", new { id=item.File_id })
    </td>
</tr>
}

Upvotes: 0

Views: 7633

Answers (3)

shrekDeep
shrekDeep

Reputation: 2328

return View(db.Files.OrderBy(col=>col.Expiry_date).ToList());

Or replace Expiry_date with any other column you want to sort on.

Upvotes: 1

SpiderCode
SpiderCode

Reputation: 10122

Order By File Name Ascending:

db.Files.OrderBy(file => file.Original_file_name).ToList();

Order By File Name Descening:

db.Files.OrderByDescending(file => file.Original_file_name).ToList();

Multiple Order By:

db.Files.OrderBy(file => file.Original_file_name).ThenBy(file => file.Expiry_date).ToList();

You can also refer: MSDN: LINQ Sorting Operations

Upvotes: 2

L-Four
L-Four

Reputation: 13531

Like:

 db.Files.OrderBy(f => f.Expiry_date).ToList();

or

 db.Files.OrderByDescending(f => f.Expiry_date).ToList();

Upvotes: 1

Related Questions