2010-11-11 46 views
-1

我有以下代码:ASP.NET MVC2简单的LINQ问题

 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); 
    } 

此代码返回从给定的类别中有些商家。

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

非常感谢, Ĵ

+0

为什么你需要做的GroupBy当你无论如何选择单行? – 2010-11-11 16:54:00

+0

你想分组什么?你为什么包括上市?你的小组的那部分是由或不相关? – 2010-11-11 16:56:05

+0

对不起,我已更新我的问题添加完整的代码,基本上我有一个分类网站。我有不同的类别,在这些类别中我有列表,这个页面只是检索该特定类别的列表...但是如何改变这些列表的顺序? – JHarley1 2010-11-11 17:00:24

回答

1

你想用OrderBy()OrderByDescending()取决于上的要求。

例如由最高价责令 -

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

你好,感谢upthecreek的建议和用词不当。我将如何搜索搜索标准字符串的内容? – JHarley1 2010-11-11 17:12:26

+0

我恐怕不完全明白...但如果你的意思是按字符串值动态排序-http://stackoverflow.com/questions/41244/dynamic-linq-orderby – Vishal 2010-11-11 17:15:33

+0

使用switch语句,测试每个字符串,你是期待,在每种情况下执行不同的查询... http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx – UpTheCreek 2010-11-11 19:26:12

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

可能的工作,这取决于你如何将信息呈现的另一种选择:使用类似的jQuery tablesorter插件,并且在客户端对结果进行排序。

显然,如果有很多结果,并且您正在进行分页,但是对于表单中显示的单页结果,这将不起作用。

0

另一种方式来写的LINQ是使用查询语言:

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