I believe you can send a list of strings to LINQ-to-SQL for a contains
.
I was wrong. But what you can do is make an enormous Where
clause. I wouldn't recommend this if there are going to be a lot of strings to compare, but test and see.
var strings = TextBox1.Text.Split(' ').ToList();
var query = from product in dc.catalog select product;
foreach (var s in strings)
{
query = query.Where(product => product.Name.Contains(s));
}
return query;
This will create something like
var query = from product in dc.catalog
where product.Name.Contains(string1)
where product.Name.Contains(string2)
where product.Name.Contains(string3)
// etc
select product;
It's pretty horrible, but if you only have a few strings it might do.
Update: To explain how the foreach
loop works, consider the original query
from product in dc.catalog select product
Let's say your textbox contains "Hello World". I'll split that into a list like { "Hello", "World" }
, and then iterate the list.
First in the list is "Hello". The line query = query.Where(product => product.Name.Contains(s));
causes the expression to become
from product in dc.catalog select product
.Where(product => product.Name.Contains("Hello"))
It's not executed yet - it's just an expression tree - but the Where
has been tagged on to the original query.
Second is "World", and the expression is appended
from product in dc.catalog select product
.Where(product => product.Name.Contains("Hello"))
.Where(product => product.Name.Contains("World"))
This does not read the same as "Contains Hello && World", but it is logically equivalent - the product
will be tested to see if it contains "Hello", and if it does then it will be tested to see if it contains "World". It has to contain both to 'pass'.
Concatenating expressions like this is exactly the same as concatenating strings.
var letters = new List<string>(){ "H", "e", "l", "l", "o" };
string result = ""
foreach (var letter in letters)
{
result = result + letter;
}
The value of result
will not be "o". It will be "Hello".