我有一种情况,我在表格中有关键字列,其中包含逗号分隔的关键字。用户可以提供多个搜索字词来搜索关键字列。例如,用户提供以下搜索项“一,二,三”,并且db列可以包含“one”,“two”,“three”或它们中的任何一个。如何编写与任何提供的搜索词匹配的查询。
我试过以下
string[] searchTerm = {"one","two","three"};
query =Product.Where( p=> searchTerm.Any(val => p.Keywords.Contains(val)));
和
var query=db.Products;
foreach (string searchword in searchTerm)
{
query = query.Where(c => c.Keywords.Contains(searchword ));
}
但它不适合我。
谢谢,
答案 0 :(得分:1)
如果您将用户提供的文本拆分为不同的关键字,如在字符串[]中转换“一,二”,三“,则可以执行以下操作:
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();
}
示例:
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);
}
打印:
one, two, three
one, three