如何像 C# 中給定串列中的值一樣對 ILookup 的鍵進行排序?
我找到了這兩個鏈接,但不明白該怎么做。
如何對查找進行排序?
從另一個串列 ID 對串列進行排序
static void Main()
{
// list with category ids (order is given by internal logic)
List<long> sortedList = new List<long> { 533, 321, 752, 251, 985 };
// create the lookup with CategoryId as Key for the products
// lookup already exists in original code and is needed before and after the reordering
List<Product> products = new List<Product>();
products.Add( new Product { Id = 23, CategoryId = 752 } );
products.Add( new Product { Id = 24, CategoryId = 752 } );
products.Add( new Product { Id = 25, CategoryId = 533 } );
products.Add( new Product { Id = 26, CategoryId = 321 } );
products.Add( new Product { Id = 27, CategoryId = 321 } );
ILookup<long, Product> lookupUnsorted = products.ToLookup( prod => prod.CategoryId, prod => prod );
// how can I sort the lookup, that the keys are sorted like in the sortedList?
// I tried something like that (which gets a converting error)
ILookup<long, Product> lookupSortedBySortedList = lookupUnsorted
.OrderBy( p => sortedList.IndexOf( p.Key ) ).ToLookup( prod => prod.Key, prod => prod );
// I also thought about iterating over the sortedList
// and add the items from the existing lookupUnsorted to a new Lookup, but it's not possible to add items to a lookup
// or with LINQ or the help of Join?
}
class Product
{
public long Id { get; set; }
public long CategoryId { get; set; }
}
謝謝。
uj5u.com熱心網友回復:
要排序,Join sortedList使用lookupUnsorted,
然后將via 中的IGrouping實體展平
并應用新的.lookupUnsortedSelectManyToLookup
var lookupSortedBySortedList = sortedList
.Join(lookupUnsorted,
categoryId => categoryId,
groupOfProducts => groupOfProducts.Key,
(categoryId, groupOfProducts) => groupOfProducts
)
.SelectMany(groupOfProducts => groupOfProducts)
.ToLookup(product => product.CategoryId, product => product);
或者,繼續嘗試使用OrderBy,可能如下所示。
var lookupSortedBySortedList = lookupUnsorted
.OrderBy(groupOfProducts => sortedList.IndexOf(groupOfProducts.Key))
.SelectMany(groupOfProducts => groupOfProducts)
.ToLookup(product => product.CategoryId, product => product);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396288.html
