Explain Codes LogoExplain Codes Logo

C# Version Of SQL LIKE

sql
regex-pattern-matching
csharp-implementation
string-matching
Alex KataevbyAlex Kataev·Dec 28, 2024
TLDR

Harness the power of Regex.IsMatch in C# for complex patterns, or stick with built-in string methods for simple searches:

// Picture this Regex as your all-seeing eye on a pattern-seeking mission! bool isMatch = Regex.IsMatch(inputString, "^.*text.*$"); // SQL version: '%text%'

Apply Contains, StartsWith, and EndsWith for standard comparisons:

// Contains() will do the detective work. Sure, it's no Sherlock, but it gets the job done! bool contains = inputString.Contains("text"); // SQL version: '%text%'

For a not-so-standard-case, create your own Like() method using regex or string extensions. More on this below.

Elaborating on pattern matching

You've entered the deep dive section. Prepare yourself for some nuggets of wisdom.

Regex-ual healing: Crafting a Like() method

Regular expressions are sort of like the Swiss army knife of pattern matching. They offer more flexibility compared to SQL's LIKE. Want an example? Here's a custom Like() function:

// Not your grandma's Like function (No offense to grandma's coding skills!) public static bool Like(this string s, string pattern) { pattern = "^" + Regex.Escape(pattern).Replace("%", ".*").Replace("_", ".") + "$"; return Regex.IsMatch(s, pattern); }

Filling in the blanks: One-character wildcard

SQL has _ as its wildcard flyweight champion–one character, any character. In the regex playground, . does the same trick. Blend this logic within your own Like() function, and BAM, you've got wildcard support!

The art of collection filtering with LINQ

Want to sift through collections as smoothly as you'd glide through a recipe book? LINQ to the rescue. Chain it with string methods or your own regex-powered Like() to filter collections like a boss:

// Just Like() that super handy kitchen sieve, but for data! var matches = myCollection.Where(x => x.Like("P%r_"));

Diving deeper with extension methods

When standard measures don't suffice, and you crave advanced capabilities, consider fabricating your own extension methods. Customized pattern matching, tailed-fit for your app, is now within your reach!

Inspect, double check: Testing

Coded your custom string matching methods? Great! Test them with diverse real-world scenarios to confirm their correctness and robustness. Remember, edge cases are sneaky!

Balance the scales: Performance considerations

Be warned: complex regex can demand a heavy performance toll. Strive to optimize your functions, perhaps via regex object caching or simpler string methods for straight-cut patterns.

References