text searching using LINQ
In the past I had covered Record Search with LINQ and that worked well, but did
not cover text searching.
Since you can't nest if-thens inside of a LINQ query it can be tough to get a useful
text search. Here is a method using a string array to search through a
field for matches.
First thing is to take a TextBox and Split the Text to put it into a string
array, but, it is not that simple. Since Linq can not make dynamic queries, we are going to have to run through an array with a set size.
For this example I will choose 5, which will limit our search to only the first 5 terms. You could easily make this more, but this is a demo damn it.
Once we decide that, we want to fill the array with String.Empty values as nulls will error out anything.
int
wordLimit =
5;
string[]
keywords =
new
string[wordLimit];
for
(int
i =
0;
i < wordLimit; i++) keywords[i] =
string.Empty;
string[]
inputKeywords = txtTitle.Text.Split(new
char[]
{
' ',
',',
''
}, wordLimit +
1,
StringSplitOptions.RemoveEmptyEntries);
int
max = inputKeywords.Length > wordLimit ? wordLimit : inputKeywords.Length;
for
(int
i =
0;
i < max; i++)
keywords[i] = inputKeywords[i];
This may seem like a lot, but this makes sure we get an array of exacly 5
elements that there are no empties in. That way, if the user does not fill
it in, *every* string contains a String.Empty, so it will work fine.
Next we just go and run through all the
strings comparing it in this example to the 'title' property
return from
p in someIQueryable where
p.title.Contains(keywords[0])
&&
p.title.Contains(keywords[1])
&&
p.title.Contains(keywords[2])
&&
p.title.Contains(keywords[3])
&&
p.title.Contains(keywords[4])
select p;
Right... now this isn't the most beautiful and elegant solution, but it works! it can be expanded to whatever size you want and will be accurate.
It may seem like a lot of lines of code, but without dynamic LINQ query production, this is the only way I found it works stock.
Simple and to the point!