gpt4 book ai didi

c# - 选择前 N 个元素并记住出现的顺序

转载 作者:行者123 更新时间:2023-11-30 21:41:41 25 4
gpt4 key购买 nike

我需要从大量产品中选择相关产品的前 N 元素。到目前为止,我有以下代码并且运行良好。

class Product
{
public string Name;
public double Rating;
public List<Product> RelatedProducts;

public List<Product> GetTopRelatedProducts(int N)
{
var relatedSet = new HashSet<Product>();
var relatedListQueue = new Queue<List<Product>>();
if (RelatedProducts != null && RelatedProducts.Count > 0)
relatedListQueue.Enqueue(RelatedProducts);
while (relatedListQueue.Count > 0)
{
var relatedList = relatedListQueue.Dequeue();
foreach (var product in relatedList)
{
if (product != this && relatedSet.Add(product) && product.RelatedProducts != null && product.RelatedProducts.Count > 0)
relatedListQueue.Enqueue(product.RelatedProducts);
}
}
return relatedSet.OrderByDescending(x => x.Rating).Take(N).OrderBy(/*How to order by occurrence here? */).ToList();
}
}

现在,我希望 GetTopRelatedProducts 方法记住前 N 产品的出现顺序。第一个添加到 HashSet 的产品将位于返回列表的开头。

例如,如果我有这个场景:

//...
relatedSet.Add(new Product(){Name="A", Rating=3});
relatedSet.Add(new Product(){Name="B", Rating=4});
relatedSet.Add(new Product(){Name="C", Rating=5});
//...

如果 N = 2,该方法应该返回:B,C 而不是 C,B 因为 B 首先被添加到 HashSet

所以我把方法中的return语句改成了:

        var relatedSetCopy = relatedSet.ToList();
return (from p in relatedSet.OrderByDescending(x => x.Rate).Take(N)
join c in relatedSetCopy on p.Name equals c.Name
let index = relatedSetCopy.IndexOf(c)
orderby index
select p).ToList();

基本上,我使用 LINQ Join 以与对 Rating 排序之前相同的方式重新排序列表。

我想这样做是因为第一个添加的产品与所选产品的相似性高于其他产品。

这里有两个问题:

  1. 有没有更好的方法来重新排序返回的列表?
  2. 是否有更好的设计来处理产品之间的关系? (我在考虑实现树结构。这样对象导航和检索会更快)

最佳答案

Is there a better way to re-order the returned list?

你可以简单地Intersect relatedSet 具有前 N 个相关的重新排序集,因为 Intersect 根据项目在第一个序列中的顺序生成项目。

所以代替

return relatedSet.OrderByDescending(x => x.Rating).Take(N).ToList();

你会用

return relatedSet.Intersect(relatedSet.OrderByDescending(x => x.Rating).Take(N)).ToList();

关于c# - 选择前 N 个元素并记住出现的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com