Tola
Tola

Reputation: 2421

Search for whole word with Linq to SQL

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.

Upvotes: 1

Views: 1746

Answers (3)

eKek0
eKek0

Reputation: 23319

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

Upvotes: 0

Jose Basilio
Jose Basilio

Reputation: 51548

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

Upvotes: 2

Jason N. Gaylord
Jason N. Gaylord

Reputation: 8324

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

Upvotes: 0

Related Questions