2009-01-28

LINQ Where Like 的And串接搜尋

簡單的例子:
在做Google搜尋時大家習慣查LINQ空格ASP.NET
轉成SQL語法是
Select * From Google Where Keyword Like '%LINQ%' And Keyword Like '%ASP.NET%'
這段語法大家一定會寫!
可是轉成LINQ呢?
大家一定覺得很簡單


For Each kw As String In Keywords.Trim.Split(" ")
query = query.Where(Function(k As Google) k.Keyword.Contains(kw))
Next


呵呵!以上是錯誤的示範,編譯會成功
但是無法執行,原因為
Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.
筆者查了好久!也有一堆人問為何這樣不行
原來只要加上一行就好了

For Each kw As String In Keywords.Trim.Split(" ")
Dim Key As String = kw
query = query.Where(Function(k As Google) k.Keyword.Contains(Key))
Next


真是江湖一點訣,知道了就很容易

0 comments: