简体   繁体   English

LINQ中的全字搜索

[英]Whole word search in LINQ

How can I search for whole word in LINQ? 如何在LINQ中搜索整个单词?

If I am searching for a word "car" in a list of strings {"carpenter","car repair","carrying","car workshop"} etc. And the result should be "car repair" & "car workshop" only . 如果我在字符串列表中搜索单词“car” {"carpenter","car repair","carrying","car workshop"}等等,结果应该是“汽车修理”和“汽车工作坊”只要 。 I tries the below code 我尝试下面的代码

  List<string> _tags = (from item in string_array
                                 where item.ToLower().Contains(search_term)
                                 select item).ToList();

But, contains always return similar words and I found this link on SO Linq Regex for whole word search which is not providing a complete answer using Regx. 但是,包含总是返回相似的单词,我在SO Linq Regex上找到了这个链接, 用于全字搜索 ,这并没有提供使用Regx的完整答案。

So, anyone can help to write an answer in Regx or is any other options to use with Linq. 因此,任何人都可以帮助在Regx中编写答案,或者是与Linq一起使用的任何其他选项。

Try this: 尝试这个:

var result = items.Where(i => i.Split(' ').Any(word => word.ToLower() == "car")).ToList();

If you need to take into account commas, you can use this instead: 如果您需要考虑逗号,可以使用此代码:

var reg = new Regex("\\bcar\\b", RegexOptions.IgnoreCase);

var items = new [] { "carpenter", "car repair", "carrying", "car workshop", "car, repair", "car. repair", "car,repair" };
var result = items.Where(word => reg.IsMatch(word)).ToList();

Gives: 得到:

car repair 
car workshop 
car, repair 
car. repair 
car,repair
list.Where(item=>item.Split(' ').Contains("car"));

You can do the following: 您可以执行以下操作:

  • Split each item in the array on white space using string.Split() 使用string.Split()拆分数组中的每个项目在空白区域
  • Search for the word using Contains using StringComaparer overload 搜索用这个词Contains使用StringComaparer 超载

like: 喜欢:

string[] string_array = {"carpenter", "car repair", "carrying", "car workshop"};
string word = "car";
 List<string> _tags = string_array.Where(r => r.Split()
                               .Contains(word, StringComparer.InvariantCultureIgnoreCase))
                                  .ToList();

For output: 输出:

foreach (var item in _tags)
{
    Console.WriteLine(item);
}

Output would be: 输出将是:

car repair
car workshop

I'd just look for a spaces before and after search keyword. 我只是在搜索关键字之前和之后寻找空格。

   List<string> _tags = string_array.Where(
       s => s.ToUpper().Contains(" " + search_term.ToUpper()) ||   
         sToUpper().Contains(search_term.ToUpper() + " ") || s.ToUpper == search_term.ToUpper()).ToList();
  var strResult = strings.Where(x => x.Split(' ').Any(y => y.Equals("car"))).ToList();

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

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