Skip to content

Instantly share code, notes, and snippets.

@AdamLJohnson
Created January 31, 2012 17:28
Show Gist options
  • Save AdamLJohnson/1711718 to your computer and use it in GitHub Desktop.
Save AdamLJohnson/1711718 to your computer and use it in GitHub Desktop.
LINQ using Wildcards
// 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("\\?", ".") + "$";
}
}
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