按给定列表对查找进行排序

Sort a Lookup by a given List

如何像 C# 中给定列表中的值一样对 ILookup 的键进行排序?
我找到了这两个链接,但不明白该怎么做。
How to sort a lookup?
Sort a list from another list IDs

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

谢谢。

排序,Join sortedListlookupUnsorted,
然后通过 SelectMany
展平 lookupUnsorted 中的 IGrouping 个实例 并应用新的 ToLookup.

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