C# 查找两个字符串之间匹配单词的百分比

C# finding percent of matched words between two string

我有一个字符串要与字符串列表进行比较以找到最佳匹配。

例如,

string search = "Orange Black Red One Five"

字符串列表可以包含以下内容

l[0] = "Orange Seven Three Black"
l[1] = " Nine Eight Seven Six"
l[2] = " Black Blue Purple Red Five Four Nine Ten"

l[0] contains 2 matches
l[1] contains 0 matches
l[2] contains 3 matches

所以程序会选择 l[2] 作为最佳匹配,匹配率为 60%。
我将如何比较两个这样的字符串?

  1. 将字符串拆分为数组。
  2. 确定匹配数。
  3. 划分。
  4. ...
  5. 盈利!

代码:

double Compare(string a, string b)
{
    var aWords = a.Split(' ');
    var bWords = b.Split(' ');
    double matches = (double)aWords.Count(x => bWords.Contains(x));
    return matches / (double)aWords.Count();
}

编辑:或者,如果您只想获取匹配计数...

int Matches(string a, string b)
{
    var aWords = a.Split(' ');
    var bWords = b.Split(' ');
    return aWords.Count(x => bWords.Contains(x));
}
    var s = search.Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries);

    var res1 = (from string part in l
        select new
        {
            list = part,
            count = part.Split(new char[] {' '}).Sum(p => s.Contains(p) ? 1 : 0)

        }).OrderByDescending(p=> p.count).First();

    Console.Write(res1.count);