「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;