Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whole word search in LINQ

Tags:

c#

linq

How can I search for whole word in 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 . 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, anyone can help to write an answer in Regx or is any other options to use with Linq.

like image 795
Sebastian Avatar asked Jul 06 '15 07:07

Sebastian


2 Answers

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
like image 58
Rob Avatar answered Nov 01 '22 13:11

Rob


list.Where(item=>item.Split(' ').Contains("car"));
like image 36
Gaurav Gupta Avatar answered Nov 01 '22 15:11

Gaurav Gupta