我正在设法从一个列表中查找一个单词或多个单词。用户输入单词,并根据名称从ItemList获取有关该项的信息。
例如:
PriceList[0].name="Black Sheep"
PriceList[1].name="Black Horse"
PriceList[2].name="White Horse"
PriceList[3].name="White Sheep"列表中的某些项,其中PriceList是ItemList,如下所示:
public class ItemList
{
public int amount { get; set; }
public string name { get; set; }
public int buyprice { get; set; }
public int sellprice { get; set; }
public int stock { get; set; }
}这就是我想要我的代码做的:
等。
我目前有:
int nickindex = PriceList.FindIndex(x => x.name.Split().Contains(typeToAdd));其中typeToAdd是用户输入字符串。
但是,这只返回一个索引,对于案例5和更高版本,它将失败。
我如何循环所有索引以找到它们?我也需要能够搜索短语而不是单词。最后,如果没有找到匹配项,我需要在单词中搜索(案例7)。
我看过Algorithm to find keywords and keyphrases in a string,但对我没有多大帮助。
任何帮助都将不胜感激。谢谢。
发布于 2014-03-27 08:13:32
您可以使用Select的重载,它为您提供了初始化匿名类型的索引:
string[] words = "Black Horse".Split();
IEnumerable<int> indices = PriceList
.Select((pl, index) => new { pl, index })
.Where(x => words.Intersect(x.pl.name.Split()).Any())
.Select(x => x.index);我使用Enumerable.Intersect检查输入字符串中的一个单词是否与名称中的一个单词匹配。
如果您想按匹配的数量降序:
IEnumerable<int> indices = PriceList
.Select((pl, index) => new
{
pl,
index,
matches = words.Intersect(pl.name.Split()).Count()
})
.Where(x => x.matches > 0)
.OrderByDescending(x => x.matches)
.Select(x => x.index);然而,这并没有涵盖你的最后一个例子,因为它没有比较词语的相似性。您可以使用Levenshtein算法。你的规则在6-8的时候也不太清楚。
https://stackoverflow.com/questions/22681626
复制相似问题