ASP.NET MVC2简单的Linq问题

时间:2010-11-11 16:51:24

标签: linq asp.net-mvc-2

我有以下代码:

      public ActionResult ViewCategory(string categoryName, string searchCriteria = "Price")
    {
        // Retrieve Category and its associated Listings from the database
        var categoryModel = db.Categories.Include("Listings")
            .Single(c => c.Title == categoryName);

        var viewModel = new ClassifiedsBrowseViewModel
        {
            Category = categoryModel,
            Listings = categoryModel.Listings.ToList()
        };

        return View(viewModel);
    }

此代码返回给定类别的一些列表。

但我想根据某些标准重新排序这些搜索结果。例如。价格...

非常感谢, Ĵ

4 个答案:

答案 0 :(得分:1)

Listings = categoryModel.Listings.OrderBy(x => x.Price).ToList();

答案 1 :(得分:1)

您希望根据要求使用OrderBy()OrderByDescending()

例如按最高价格订购 -

var viewModel = new ClassifiedsBrowseViewModel
        {
            Category = categoryModel,
            Listings = categoryModel.Listings.OrderByDescending(c=>c.Price).ToList()
        };

答案 2 :(得分:0)

另一个可能有效的选项,取决于您如何呈现信息:使用类似jquery tablesorter插件的内容,并在客户端对结果进行排序。

显然,如果有很多结果,并且你正在进行分页,这将无效。但是对于单页结果,在表格中显示,它的效果很好。

答案 3 :(得分:0)

编写Linq的另一种方法是使用查询语言:

Listings = from item in categoryModel.Listings
           orderby item.Price
           select item;