字符串比较,返回最相似

时间:2016-10-09 17:26:09

标签: c# string entity-framework comparison

从字符串中搜索子字符串并获取与最匹配的子字符串!

string [] allModels = { "Galaxy", "S3", "Galaxy S3" };
string title = "Samasung galaxy s3 is for sale";
string[] title_array = title.Split(' ');
string model = "";
foreach(var tit in title_array)
{
      foreach(var mod in allModels)
      {
             if (mod.Equals(tit, StringComparison.OrdinalIgnoreCase))
             {
                   model = mod;
             }
      }
}

所选模型为Galaxy,但我需要Galaxy S3(即最相似)。我怎样才能获得Galaxy S3

我应该使用Array.FindAll(target)方法吗?

更新

most similar我的意思是与字符串(标题)匹配最多的子字符串(模型)

例如,在galaxy Samasung s3 is for sale中,模型应为galaxy s3(根据上述allModels数组)

2 个答案:

答案 0 :(得分:0)

Most similar?不一定是Search substrings from a string and get a substring that matches the most!我认为你想要一个最长的比赛......

string[] allModels = { "Galaxy", "S3", "Galaxy S3" };
string title = "Samasung galaxy s3 is for sale";

var mod = allModels.OrderByDescending(x => x.Length)
          .FirstOrDefault(x => title.IndexOf(x,StringComparison.OrdinalIgnoreCase)>=0);

答案 1 :(得分:0)

这是一种查找包含标题最多单词的模型的方法。

var allModelsList = new List<String>(allModels);
var titles = new List<String>(title_array);
allModelsList.OrderByDescending(model => titles.Where(title => title.Equals(model, StringComparison.OrdinalIgnoreCase)).Count()).FirstOrDefault();
相关问题