Created
January 31, 2012 17:28
-
-
Save AdamLJohnson/1711718 to your computer and use it in GitHub Desktop.
LINQ using Wildcards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: http://stackoverflow.com/questions/3102250/linq-search-using-wildcards-character-like | |
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<T> MatchesWildcard<T>(this IEnumerable<T> sequence, Func<T,string> expression, string pattern) | |
{ | |
var regEx = WildcardToRegex(pattern); | |
return sequence.Where(item => Regex.IsMatch(expression(item), regEx)); | |
} | |
public static string WildcardToRegex(string pattern) | |
{ | |
return "^" + Regex.Escape(pattern). | |
Replace("\\*", ".*"). | |
Replace("\\?", ".") + "$"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var items = new[] { new MyObj { MyProperty = "ABC123" }, | |
new MyObj { MyProperty = "123ABC" }, | |
new MyObj { MyProperty = "123ABC456" }, | |
}; | |
var matches = items.MatchesWildcard(item => item.MyProperty, "???ABC"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment