Erweiterungsmethode: String.Like

Hier eine kleine Erweiterungsmethode, die ein SQL Like auf Strings ermöglicht:


public static bool Like( this string value, string pattern )
{
    string parsedPattern = "\\A" + Regex.Escape( pattern ).Replace( "\\*", ".*" ).Replace( "\\?", "." ) + "\\Z";

    Regex regex = new Regex(parsedPattern, RegexOptions.IgnoreCase);

    return regex.IsMatch(value);
}

Die Funktion eignet sich, wenn ich statt einer Linq-Abfrage einen Lamda-Ausdruck verwenden will/muss:


List<string> theSimpsons = new List<string>(){"Homer", "Bart", "Marge", "Lisa", "Maggie"};

Func<string, bool> matchCriteria = person => person.Like("*ar*");
Debug.WriteLine( "*ar*" );

foreach (string character in theSimpsons.Where(matchCriteria))
{
    Debug.WriteLine( character );
}

matchCriteria = person => person.Like( "M*i*" );
Debug.WriteLine( "M*i*" );
foreach( string character in theSimpsons.Where( matchCriteria ) )
{
    Debug.WriteLine( character );
}

matchCriteria = person => person.Like( "M*e" );
Debug.WriteLine( "M*e" );
foreach( string character in theSimpsons.Where( matchCriteria ) )
{
    Debug.WriteLine( character );
}

matchCriteria = person => person.Like( "*a*" );
Debug.WriteLine( "*a*" );
foreach( string character in theSimpsons.Where( matchCriteria ) )
{
    Debug.WriteLine( character );
}

matchCriteria = person => person.Like( "*a" );
Debug.WriteLine( "*a" );
foreach( string character in theSimpsons.Where( matchCriteria ) )
{
    Debug.WriteLine( character );
}


Ausgabe:
*ar*
Bart
Marge
M*i*
Maggie
M*e
Marge
Maggie
*a*
Bart
Marge
Lisa
Maggie
*a
Lisa

Kick It auf dotnet-kicks.de

Leave a Reply

Your email address will not be published.


*