[英]LINQ order by a number sequence
我有一個帶有類別ID的產品列表,例如:
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有什么辦法嗎? 謝謝
如果您的類別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 to Objects,因此您需要從數據庫中取消所有數據。
假設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(nm)。
您可以使用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
var query = from p in productsList
orderby p.CategoryID descending
select new {ID = p.ID, CID = p.CategoryID, PName = p.ProductName};
query
現在包含無序序列的產品列表。 您可以通過它枚舉如下:
foreach(Product prod in query)
Console.WriteLine(prod.CID);
編輯:誤解了答案。 將更新答案。
如果您知道要在列表頂部排序的所有內容,請嘗試以下操作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.