Sebastian
Sebastian

Reputation: 4811

Whole word search in 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.

Upvotes: 14

Views: 6178

Answers (5)

Habib
Habib

Reputation: 223402

You can do the following:

  • Split each item in the array on white space using string.Split()
  • Search for the word using Contains using StringComaparer overload

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

Upvotes: 2

Kumod Singh
Kumod Singh

Reputation: 2163

  var strResult = strings.Where(x => x.Split(' ').Any(y => y.Equals("car"))).ToList();

Upvotes: 1

Gaurav Gupta
Gaurav Gupta

Reputation: 324

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

Upvotes: 2

Rob
Rob

Reputation: 27367

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

Upvotes: 18

Fabjan
Fabjan

Reputation: 13676

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();

Upvotes: 1

Related Questions