LINQ按数字顺序排序
我有一个产品列表与他们的类别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到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)。
如果您知道要在列表顶部排序的所有内容,请尝试以下操作:
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
链接地址: http://www.djcxy.com/p/34277.html