我试图弄清楚如何按关键字过滤列表,但过滤它具有大多数关键字但不需要全部关键字的位置。
关键词:
{"test", "find", "me","where","am","i"}
清单将是:
{ "find me", "test where am i", "find me where am i"}
我想要的输出是:
"find me where am i"
您可以使用以下内容:
var keywords = new List<string> { "test", "find", "me", "where", "am", "i" };
var list = new List<string> { "find me", "test where am i", "find me where am i" };
var filtered =
list.Select(li => (item: li, count: keywords.Count(k => li.Contains(k))))
.GroupBy(x => x.count)
.OrderByDescending(g => g.Key)
.First()
.Select(x => x.item)
.ToList();
这基本上会根据关键字检查列表中的每个项目,按找到的关键字的数量进行分组,然后选择找到最多的关键字。
笔记:
Using.Contains()将接受关键字,即使它们是另一个单词的一部分。如果找到的关键字必须是整个单词(这可能是真的),您可以调整逻辑以使用正则表达式,如下所示:
list.Select(li => (item: li, count: keywords.Count(k => Regex.IsMatch(li, $@"\b{k}\b"))))