【发布时间】:2019-01-05 13:03:39
【问题描述】:
我正在尝试从列表中获取有序记录,如下所示:
static Dictionary<string, List<Recomdendations>> productRecomdendationss = new Dictionary<string, List<Recomdendations>>();
public List<Recomdendations> TopMatches(int id)
{
var name = db.Books.SingleOrDefault(x=>x.Id==id).BkName;
List<Recomdendations> books = LoadBooks().ToList();
productRecomdendationss.Add(name,books);
// grab of list of products that *excludes* the item we're searching for
var sortedList = productRecomdendationss.Where(x => x.Key != name);
sortedList.OrderByDescending(x => x.Key);
List<Recomdendations> Recomdendationss = new List<Recomdendations>();
// go through the list and calculate the Pearson score for each product
foreach (var entry in sortedList)
{
Recomdendationss.Add(new Recomdendations() { bookName =entry.Key , Rate = CalculatePearsonCorrelation(name, entry.Key) });
}
return Recomdendationss.OrderByDescending(x=> x.Rate).ToList();
}
当我尝试在以下行中将记录添加到列表时出现问题:
foreach (var entry in sortedList)
{
Recomdendationss.Add(new Recomdendations() { bookName =entry.Key , Rate = CalculatePearsonCorrelation(name, entry.Key) });
}
它只将最后一条记录添加到列表中,而我要求将所有记录作为有序记录添加到列表中。那么我应该如何修改代码以返回列表中的所有建议。我调试了代码,发现这行代码有问题。
【问题讨论】:
-
sortedList.OrderByDescending(x => x.Key)不会改变sortedList- 它只是返回一个有序序列,然后您将忽略它。我怀疑你想要var sortedList = productRecomdendationss.Where(x => x.Key != name).OrderByDescending(x => x.Key); -
代码按预期工作。这意味着您不了解一些基本概念,但您需要了解它们才能提出正确的问题 - 或者至少知道您不知道什么,以便您可以指出您的问题方向。我将此标记为关闭。
标签: c# dictionary foreach