用LINQ匹配大多数匹配词

本文关键字:大多数 LINQ | 更新日期: 2023-09-27 18:04:43

我想写一个LINQ查询,它将返回最匹配的单词的记录,按匹配的单词数排序。单词不必按顺序排列

输入:

"word3 word2"

字符串数组:

"word1 word2 word3 word4 word5"
"word1 word2"
"word4 word5"
"word1 word4 word5"

输出将是

"word1 word2 word3 word4 word5"
"word1 word2"

这是可行的LINQ吗?

用LINQ匹配大多数匹配词

可以用Linq来完成。

例子:

var wantedWords = "word3 word2".Split();
var strings = new List<string>
{
    "word1 word2 word3 word4 word5",
    "word1 word2",
    "word4 word5",
    "word1 word4 word5"
};
var result = from s in strings
             let words = s.Split()
             select new
             {
                 String = s,
                 MatchedCount = wantedWords.Count(ww => words.Contains(ww))
             } into e
             where e.MatchedCount > 0
             orderby e.MatchedCount descending
             select e.String;

我发现LinqRegex的组合完成了这项工作。获取输入,并将其转换为Where() Linq中使用的模式。

在这个例子中,输入被转换成

的模式
"word3|word2"

我们使用它来查找数组中具有word3 OR(管道字符在Regex中表示OR) word2的行。

string input = "word3 word2";
string[] array = 
{
    "word1 word2 word3 word4 word5",
    "word1 word2",
    "word4 word5",
    "word1 word4 word5"
};
string pattern = input.Replace(" ", "|");
List<string> results = array.Where(a => Regex.Match(a, pattern).Success).ToList();
results.ForEach(Console.WriteLine);

结果:

word1 word2 word3 word4 word5
word1 word2