如何在C#中使用String.Contains()模糊方式? [英] How to String.Contains() the Fuzzy way in C#?

查看:207
本文介绍了如何在C#中使用String.Contains()模糊方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在过滤时搜索的人员列表.每次用户输入搜索字符串,都会应用过滤.

要考虑两个挑战:

  1. 用户可以输入部分姓名
  2. 用户可能会犯错

只需搜索子字符串即可解决第一个问题,例如String.Contains().可以通过使用模糊实现来解决第二个问题(例如 https://fuzzystring.codeplex.com )

但是我不知道如何同时应对这两个挑战.

例如:输入以下其中一项时,我想找到人"Martin Fowler博士":

  • 马丁"
  • "Fawler"
  • 马丁·福勒"

我想我需要编写一个"FuzzyContains()"逻辑,该逻辑可以满足我的需求,并且具有可接受的性能.有什么建议如何开始吗?

解决方案

我修改了提供答案,建议了Levenshtein距离算法,这不是最佳选择,因为当仅输入部分名称时,计算出的距离就很大.因此,我最终使用了最长的普通子序列算法,该算法由令人敬畏的https://fuzzystring.codeplex.com)

But I don't know how to master both challenges simultaneously.

For example: I want to find the person "Dr. Martin Fowler" when entering one of:

  • "Martin"
  • "Fawler"
  • "Marten Fauler"

I guess I need to write a "FuzzyContains()" logic, that handle my needs and also has an acceptable performance. Any advices how to start?

解决方案

I modified Oliver answer who suggested the Levenshtein Distance algorithms, that is not the best choice here, since the calculated distance is to big when only parts of the names were entered. So, I ended up using the Longest Common Subsequence algorithm implemented by the awesome FuzzyString Lib.

const int TOLERANCE = 1;
string userInput = textInput.Text.ToLower();
var matchingPeople = people.Where(p =>
{
     //Check Contains
     bool contains = p.Name.ToLower().Contains(userInput);
     if(contains) return true;

     //Check LongestCommonSubsequence
     bool subsequenceTolerated = p.Name.LongestCommonSubsequence(userInput).Length >= userInput.Length - TOLERANCE;

     return subsequenceTolerated;
}).ToList();

这篇关于如何在C#中使用String.Contains()模糊方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆