Here are 2 options:
- Using the SqlMethods.Like method (recommended)
- Using the AsEnumerable method to pull down the records and use regex or such on the client side in memory (costlier)
Going with option #1 above, you could do something like this:
string searchTerm = "abccamp";
string pattern = "%"
+ String.Join("%", searchTerm.Select(c => c.ToString()).ToArray())
+ "%";
var query = from x in y
where SqlMethods.Like(x, pattern)
select x;
Adapting it to your query you would probably use something similar to SqlMethods.Like(p.Product_Name, pattern)
in place of p.Product_Name.ToLower().Contains(text.ToLower())
.
EDIT: as mentioned in the comments this approach may not yield accurate results since a wildcard exists between each character to take the place of the special characters. Another possible approach is to use _
instead of %
to account for a single character. The downside is you might have multiple special characters in a row and a wildcard would be needed for repetitions, which puts us back where we started. With SqlMethods.Like
you can use the same things available to a TSQL LIKE. This includes character classes with ranges and negated character classes, so you could also use [!/@ ]
in place of the %
in String.Join
.
The problem with using _
is that you can't make the single character optional as you would do with a regex. A pattern of a_b_c_d
doesn't match "abcd" since each _
must match a character in between each letter. In other words, it would match "a!b$c@d". Perhaps you can use both in the where
clause: ... where x == searchTerm || SqlMethods.Like(x, pattern)
where pattern
is the same as before but using a _
instead of %
in the String.Join
method.
Additionally, be sure to have some if/else logic checks around the searchTerm
to determine what to do if the input is empty or consists of a single character which would yield %x%
and may not be desirable and match many rows.