2

我有一个带有类别 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有什么办法吗?谢谢

4

5 回答 5

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)。

于 2012-08-11T20:25:33.280 回答
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,因此您需要从数据库中无序地获取所有数据。

于 2012-08-11T20:17:20.213 回答
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 
于 2012-08-11T20:27:27.223 回答
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);

编辑:误解了答案。将更新答案。

于 2012-08-11T20:14:04.570 回答
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

于 2012-08-11T20:10:23.623 回答