2012-08-11 24 views
2

我的產品列表以及它們的類別編號,如:LINQ爲了

ID  CategoryID  Product Name 
1  1    Product 1 
2  1    Product 2 
3  7    Product 3 
4  8    Product 4 
5  9    Product 5 
6  10    Product 6 

我想的categoryID列表藉此名單和順序,如:1,8,9其餘,所以我得到:

ID  CategoryID  Product Name 
1  1    Product 1 
2  1    Product 2 
4  8    Product 4 
5  9    Product 5 
3  7    Product 3 
6  10    Product 6 

有沒有什麼辦法可以與linq? 感謝

+0

通過使用'orderby'? http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b – 2012-08-11 20:09:44

+0

您首先需要在「數學」中定義您的訂單。 1,8,9,7,10不是正常的順序。您可以添加索引,如{1,1},{8,2},{9,3},{7,4},{10,5}並按索引排序。 – 2012-08-11 20:11:42

+0

如果OP錯誤地輸入了他正在尋找的結果並且它就像一個簡單的數字「orderBy」一樣簡單,那麼這真的很有趣......仍然是非常有趣且有趣的解決方案,但有趣。 – 2012-08-12 01:12:57

回答

0

您可以使用Enumerable.OrderBy

var catIDs = new[] { 1, 8, 9 }; 
var ordered = products 
    .OrderByDescending(p => catIDs.Contains(p.CategoryID)) 
    .ThenBy(p => p.CategoryID); 

編輯:這裏有一個演示:http://ideone.com/O462C

0
var query = from p in productsList 
      orderby p.CategoryID descending 
      select new {ID = p.ID, CID = p.CategoryID, PName = p.ProductName}; 

query現在包含在產品列表inordered序列。你可以通過它像枚舉:

foreach(Product prod in query) 
    Console.WriteLine(prod.CID); 

編輯:誤解了答案。將更新答案。

5

如果你的類別ID在列表中,您可以訂購這樣的:

var list = new List<int>() { 1, 8, 9, 7, 10, ... }; 

var productsOrdered = from p in products 
    let index = list.IndexOf(p.CategoryID) 
    order by (index < 0 ? int.MaxValue : index) // in case it is not in the list 
    select p; 

此查詢使用LINQ只有工作對象,所以你需要把從數據庫無序的所有數據。

+2

這會起作用,但是如果'list'非常大,那將會很糟糕。 – 2012-08-11 20:28:18

+1

你說得對。你的解決方案更好。 – 2012-08-11 20:33:05

+0

雖然取決於。低於特定數量時,您的工作就會進行 - 無需浪費時間來設置字典,迭代列表的常量因子比查找字典要低,因此對於小型集合,「IndexOf」比「TryGetValue」快。我認爲這兩種方法的價值都沒有價值。 – 2012-08-11 21:03:30

5

假設1,8,9位於列表中,我們將調用orderList,然後當我們每次都可以繼續查找列表中的位置時,我們將更快地創建一個字典來查看它迅速起來。

var orderDict = orderList.Select((o, index) => new {ID = o, Order=index}).ToDictionary(oi => oi.ID, oi => oi.Order); 
int orderHolder; 
var orderedProducts = products.OrderBy(p => orderDict.TryGetValue(p.CategoryID, out orderHolder) ? orderHolder : int.MaxValue); 

我們不嚴格需要建立orderDict第一,但它使邏輯不是通過列表每次掃描更簡單,也更快:O(N + M),而不是O(納米) 。

0

如果你知道你要在列表頂部的排序一切,試試這個:

var products = new List<Product>(); 

products.Add(new Product { ID = 1, CategoryID = 1, ProductName = "1" }); 
products.Add(new Product { ID = 2, CategoryID = 1, ProductName = "2" }); 
products.Add(new Product { ID = 3, CategoryID = 7, ProductName = "3" }); 
products.Add(new Product { ID = 4, CategoryID = 8, ProductName = "4" }); 
products.Add(new Product { ID = 5, CategoryID = 9, ProductName = "5" }); 
products.Add(new Product { ID = 6, CategoryID = 10, ProductName = "6" }); 

products 
    .OrderByDescending(p => p.CategoryID == 1 || p.CategoryID == 8 || p.CategoryID == 9) 
    .ThenBy(p => p.CategoryID); 

產生以下(從LinqPad):

ID CategoryID ProductName 
1 1   1 
2 1   2 
4 8   4 
5 9   5 
3 7   3 
6 10   6 
+0

將第二個最後一個類別放在'products'中,它首先出現在結果中,這是不正確的。 – 2012-08-11 21:04:44