简体   繁体   中英

Search for a word in a specific column using EF or linq (C#)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM