0

What is the best way to search for a "word" in a column in database. I use the following code:

query.Where(x => x.Content.Contains(key));

The issue is if the column contains: "I am 2 years old", when searching with the word "year", it shall not find it but the previous code sample finds it.

Also, if I try to add space before and after the key like this:

query.Where(x => x.Content.Contains(" " + key + " "));

It will not find the sentence "Year ago, I had a dream.",

Also, what about capital and lower case in EF.

Kasparov92
  • 1,365
  • 4
  • 14
  • 39

1 Answers1

0

Here is a way to do this and just find whole words. Plug the following code into LinqPad to test. However, Regex is the power that makes this work and Regex is slower than .Contains.

void Main()
{
    List<string> testStrings = new List<string>();
    testStrings.Add("I am 2 years old");
    testStrings.Add("Year ago, I had a dream.");

    var searchValue = "year";
    string expression = String.Format(@"\b*((?i){0}(?-i))\b", searchValue);

    Regex regex = new Regex(expression);

    var found = testStrings.Where(s => regex.Matches(s).Count > 0);

    found.Dump();
}

The Regex works as follows:

\b*((?i){0}(?-i))\b

\b means get a whole word, (?i) means case-insensitive.