我想编写一个LINQ查询,该查询将返回匹配单词数最多的匹配单词的记录。而且这些词语不必按顺序排列
输入:
"word3 word2"
字符串数组:
"word1 word2 word3 word4 word5"
"word1 word2"
"word4 word5"
"word1 word4 word5"
输出将是
"word1 word2 word3 word4 word5"
"word1 word2"
这可以用LINQ吗?
答案 0 :(得分:0)
我发现Linq
和Regex
的组合完成了这项工作。获取输入,并将其转换为要在Where()
Linq
中使用的模式。
在此示例中,输入转换为
模式"word3|word2"
我们使用它来查找数组中有word3 OR的行(管道符代表Regex
)word2中的OR。
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
答案 1 :(得分:0)
可以使用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;