Reputation: 1692
I have a situation where i have Keyword column in table which contains comma separated keywords. User can provide multiple search terms to search against the Keyword column. For example user provides the below search terms "one,two,three" and the db column may contain any of the "one" ,"two", "three" or none of them. how can I write a query which matches against any of the provided search term.
I have tried the below
string[] searchTerm = {"one","two","three"};
query =Product.Where( p=> searchTerm.Any(val => p.Keywords.Contains(val)));
and
var query=db.Products;
foreach (string searchword in searchTerm)
{
query = query.Where(c => c.Keywords.Contains(searchword ));
}
but its not working for me.
Thanks,
Upvotes: 2
Views: 3590
Reputation: 63956
If you split the text provided by the user in different keywords, as in converting "one,two",three" in a string[], you could do something like:
string [] keys = keywords.Split(',');
var query = new List<Product>();
foreach (var item in keys)
{
query = query.Concat ((IEnumerable<Product>)Product.Where(x=>x.KeyWords.Contains(item))).ToList();
}
Example:
List<Product> ass = new List<Product>();
Product a = new Product();
a.KeyWords = "one, two, three";
Product a1 = new Product();
a1.KeyWords = "one, three";
Product a2 = new Product();
a2.KeyWords = "five";
ass.Add(a);
ass.Add(a1);
ass.Add(a2);
string userInput = "one, seven";
string [] keys = userInput.Split(',');
var query = new List<Product>();
foreach (var item in keys)
{
query = query.Concat ((IEnumerable<Product>)ass.Where(x=>x.KeyWords.Contains(item))).ToList();
}
foreach (var item in query )
{
Console.WriteLine(item.KeyWords);
}
Prints:
one, two, three
one, three
Upvotes: 1