Reputation: 1773
In my application, I have a search query textbox (txtSearch) that works well with one-word queries with the following LINQ:
slstFilteredItems = From s In slstItems _
Where s.strText.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0 _
Select s
But if you search this with a multiple-word query, say "Create customer" (no quotes), it only finds results that contain the result "Create Customer" exactly (case-insensitive).
So the simplest way to handle this that I can think of is with a query that does a .Intersect with each word in sequence, like this:
slstFilteredItems = (From s In slstItems _
Where s.strText.IndexOf(txtSearch.Text.Split(" ")(0), StringComparison.OrdinalIgnoreCase) >= 0 _
Select s).Intersect _
(From s In slstItems _
Where s.strText.IndexOf(txtSearch.Text.Split(" ")(1), StringComparison.OrdinalIgnoreCase) >= 0 _
Select s)
'And so on...
So how would I make the above query more generic (ie: able to handle any number of words in a query)?
I should note that the object being queried is a List of strings pulled from an Access database. As it stands, this application only queries the database once and I'd like to keep it that way if possible.
Upvotes: 0
Views: 2005
Reputation: 15242
This should work for an arbitrary number of items in the txtSearch.text.Split array
slstFilteredItems = (From splits In txtSearch.Text.Split(" ").ToList _
From s In slstItems _
Where s.strText.IndexOf(splits, StringComparison.OrdinalIgnoreCase) >= 0 _
Select s)
Upvotes: 1
Reputation: 2752
Here is one possible approach:
Dim words = "Dog cAt biRD"
Dim slstItems = New String() { "dog thing cat bird ", "bird cat", "cat foo dog bird " }
'Query Syntax (with some fluent syntax)
Dim q = From s In slstItems.Select(Function(x) x.ToLower())
Where words.Split(" ").Select(Function(x) x.ToLower()).All(Function(x) s.Contains(x))
Select s
'All Fluent Syntax
slstItems.Select(Function(x) x.ToLower()) _
.Where(Function(s) words.Split(" ").Select(Function(x) x.ToLower()) _
.All(Function(w) s.Contains(w)) _
)
Both return:
dog thing cat bird
cat foo dog bird
Note that this is inefficient when compared to bigtlb's answer (which is a much better solution for database searching).
Upvotes: 1
Reputation: 1572
If you are hitting a SQL Server Database, Full Text Searching may be a better approach.
http://msdn.microsoft.com/en-us/library/ms142571.aspx
Upvotes: 0