简体   繁体   English

使用EF或linq(C#)在特定列中搜索单词

[英]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. 问题是,如果该列包含:“我今年2岁”,则使用单词“ year”搜索时,将找不到它,但是以前的代码示例可以找到它。

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. 另外,EF中的资本和小写字母如何?

Here is a way to do this and just find whole words. 这是一种方法,可以查找整个单词。 Plug the following code into LinqPad to test. 将以下代码插入LinqPad中进行测试。 However, Regex is the power that makes this work and Regex is slower than .Contains. 但是,正则表达式是使此工作有效的功能,而正则表达式比.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. \\ b表示完整单词,(?i)表示不区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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