I am working on a (quick and dirty) search engine, using linq to sql. I already have a table of strings containing each word I want to search inside the descriptions of each entry.
In the end of my linq to sql process, I should get only the entries containing all the words from my table. Here is the code I have so far (m1 is my table of strings) :
var myUser = from u in dataBase.Profiles
where u.Status == 2 // some primary selection
select u;
foreach (string word in m1)
{
myUser = from u in myUser
where ((word != "") ? u.Description.Contains(word) : 1 == 1)
select u;
}
myUser = from u in myUser
orderby u.ModificationDate descending // finally, we order the list
select u;
This code works nicely, but sadly, it does not select entries containing both words, but all the entries containing at least one word.
Can you understand why? I don't : /
You are closing over the loop variable.
Closures close over variables, not over values.
Try assigning the string to a local variable:
foreach (string word2 in m1)
{
string word = word2;
myUser = from u in myUser
where ((word != "") ? u.Description.Contains(word) : 1 == 1)
select u;
}