Qash
Qash

Reputation: 167

Linq Regex for whole word search

I'm unable to find a recent decent answer on this.

Linq does not support regex, and trying to extract a method out does not outsmart the framwork. How do I do a whole work match on a list of sentences in linq.

The reason I need the \b is because it could be start or end of string, or have a comma, dash, or other similar separators.

    private bool isMatch(string searchText, string text)
    {
        return Regex.IsMatch(searchText, "\\b"+text+"\\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    }


        result  p = itemsRep
            .Where(fullText=> isMatch(searchText, fullText))
            .FirstOrDefault();

Upvotes: 1

Views: 2217

Answers (1)

Oliver
Oliver

Reputation: 9002

I think what you're saying is that Linq-to-SQL/Linq-To-Entities does not support Regex in expressions.

Try adding .AsEnumerable() before your .Where().

The .Where() method will then enumerate over the results of any translated query, rather than try to convert your .Where() expression to SQL.

Like this:

result  p = itemsRep
            .AsEnumerable()
            .Where(fullText => isMatch(searchText, fullText))
            .FirstOrDefault();

Upvotes: 2

Related Questions