我有一个带有类别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有什么办法吗? 感谢
答案 0 :(得分: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 to Objects,因此您需要从数据库中取消所有数据。
答案 1 :(得分: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(nm)
答案 2 :(得分: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
答案 3 :(得分:0)
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);
编辑:误解了答案。将更新答案。
答案 4 :(得分: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