LINQ order by a number sequence

I have a list of products with their category ID, like:

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

I want to take this list and order by a list of categoryID, like: 1, 8, 9 and the rest, so I get:

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

There is any way to this with linq? Thanks


If your category IDs are in a list, you can order like that:

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;

This query will work only with Linq to Objects, so you need to bring all data unordered from your database.


Assuming that the 1,8,9 is in a list, we'll call orderList , then while we can keep looking for the position in the list each time, we'll be faster to create a dictionary to look it up quickly.

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

We don't strictly need to set-up orderDict first, but it makes the logic simpler than scanning through the list every time, and also quicker: O(n + m) rather than O(nm).


If you know everything that you want to sort at the top of the list, try this:

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

Produces this (from LinqPad):

ID CategoryID ProductName 
1  1          1 
2  1          2 
4  8          4 
5  9          5 
3  7          3 
6  10         6 
链接地址: http://www.djcxy.com/p/34278.html

上一篇: LINQ:何时使用SingleOrDefault与FirstOrDefault()以及过滤标准

下一篇: LINQ按数字顺序排序