Alex
Alex

Reputation: 833

Sorting of IEnumerable<T> in MVC 2

My Service layer returns a IEnumerable<ResortsView> to my Controller and I have to provide an option to SORT the results on UI by following criteria: Price (Excluding ZERO Price Items), SupplierName & Rating. Here is the code snippet of my objects/classes:

[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; } 
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}

What is the best way to handle sorting of results inside IEnumerable<ResortsView>?

Upvotes: 3

Views: 1612

Answers (2)

Femaref
Femaref

Reputation: 61437

Use the OrderBy method of the LINQ stack:

IEnumerable<ResortsView> source = GetResorts();
var model = source.OrderBy(rv => rv.CheckInTime);

To order by the lowest, non-zero price in ResortProducts:

var model = source.OrderBy(rv => rv.ResortProducts.Where(p => p.Price > 0).Min(p => p.Price));

Upvotes: 3

Paul Creasey
Paul Creasey

Reputation: 28824

Most likely if you'll want to use the Dynamic LINQ library, here are some instructions and a download link.

You'll need to have your action accept some sorting parameters:

public ActionResult MyAction(string sortField)
{
    return View(myService.MyData().OrderBy(sortField));
}

Upvotes: 0

Related Questions