Tutorial :Search for whole word with Linq to SQL



Question:

I'm using VB.NET and Linq to SQL to do search query. I'm using the Contains method of Linq to look up the input keyword. It's like this note.note_content.Contains(InputKeyWord).

The problem is that If I search for the "cord" then "according" will also come up. I want the result to be matched with keyword only.

How do I do to search for the whole keyword with Linq ?

Thank you.


Solution:1

I'm assuming that the inputKeyword can appear at the beginning, any place in between and at the end of the note, therefore you need to have 3 OR clauses for the 3 possible places where it can appear. So, your LINQ where clause may end up looking like this.

note.note_content.StartsWith(InputKeyword & " ") OR _  note.note_content.EndsWith(" " & InputKeyword) OR _  note.note_content.Contains(" " & InputKeyword & " ")  

This is not a pretty solution, but It should work. If you are adept with regular expressions, that's an option with LINQ as well.

Read this: How to Combine LINQ with Regular Expressions


Solution:2

Are the delimiters or spaces around the data? You can use the .Like (InputKeyword) to refine it a bit more.


Solution:3

I guess your keywords has delimiters on the beginning and on the end. If that's true, you could use

from n in note  where n.note_content.Contains(beginDelimiter + InputKeyWord + endDelimiter) ||        n.note_content.StartsWith(InputKeyWord + endDelimiter) ||         n.note_content.EndsWith(beginDelimiter + InputKeyWord)  select n  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »