您可以创建一个名为“ContainsFuzzy”的自定义扩展方法:
public static bool ContainsFuzzy(this string target, string text){
// do the cheap stuff first
if ( target == text ) return true;
if ( target.Contains( text ) ) return true;
// if the above don't return true, then do the more expensive stuff
// such as splitting up the string or using a regex
}
那么你的 LINQ 至少会更容易阅读:
var objects = from x in db.Foo
where x.Name.ContainsFuzzy("Foo McFoo")
select x;
明显的缺点是每次调用 ContainsFuzzy 都意味着重新创建拆分列表等,因此会产生一些开销。您可以创建一个名为 FuzzySearch 的类,它至少可以提高效率:
class FuzzySearch{
private string _searchTerm;
private string[] _searchTerms;
private Regex _searchPattern;
public FuzzySearch( string searchTerm ){
_searchTerm = searchTerm;
_searchTerms = searchTerm.Split( new Char[] { ' ' } );
_searchPattern = new Regex(
"(?i)(?=.*" + String.Join(")(?=.*", _searchTerms) + ")");
}
public bool IsMatch( string value ){
// do the cheap stuff first
if ( _searchTerm == value ) return true;
if ( value.Contains( _searchTerm ) ) return true;
// if the above don't return true, then do the more expensive stuff
if ( _searchPattern.IsMatch( value ) ) return true;
// etc.
}
}
你的 LINQ:
FuzzySearch _fuzz = new FuzzySearch( "Foo McFoo" );
var objects = from x in db.Foo
where _fuzz.IsMatch( x.Name )
select x;