2009-05-01 77 views
1

我正在使用VB.NET和Linq to SQL來執行搜索查詢。我使用Linq的Contains方法來查找輸入關鍵字。就像這樣note.note_content.Contains(InputKeyWord)使用Linq to SQL搜索整個詞

問題是如果我搜索「cord」,那麼「根據」也會出現。我希望結果僅與關鍵字匹配。

如何使用Linq搜索整個關鍵字?

謝謝。

+0

爲什麼這給了-1?顯然是這個問題的答案,我很高興找到 – toy 2014-06-02 15:15:54

回答

2

我假設inputKeyword可以出現在開始處,中間和結束處的任何地方,因此您需要在3個可能出現的地方有3個OR子句。所以,你的LINQ where子句最終可能會看起來像這樣。

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

這不是一個漂亮的解決方案,但它應該工作。如果你擅長正則表達式,那麼LINQ也是一個選項。

閱讀本:How to Combine LINQ with Regular Expressions

+0

如果你向我們展示如何用正則表達式來做這件事,那會很好。 – 2009-05-01 04:24:18

0

數據周圍是分隔符還是空格?您可以使用.Like(InputKeyword)進一步優化它。

+0

我不認爲我們有像方法。 – 2009-05-01 04:25:48

+0

你應該有Like方法。 – 2009-05-01 19:31:17

0

我猜你的關鍵字對開始和結束的分隔符。如果這是真的,你可以使用

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