2010-11-11 48 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;