[英]Searching names by each word in search string
我正在尝试在我的 asp.net mvc 网站中构建搜索。 例如,我想返回与搜索字符串中具有任何关键字匹配项的产品相匹配的产品。 例如,我有这样的产品,
目前,如果我搜索“rgb strip”,我不会从搜索中得到任何结果。 如果我搜索“rgb strip”,我需要从搜索文本中返回具有“rgb”和“strip”关键字的前两个产品。 在当前的功能范围内,如果我搜索“rgb”,它会返回以上 3 个产品。 我需要实现一种搜索产品的机制,其中包含产品名称中的每个单词。 但我不知道如何去做。 可以请任何人帮助我吗? 谢谢你。
当前搜索功能,
public List<Product> SearchProducts(List<int> categoryIDs, string searchTerm, decimal? from, decimal? to, string sortby, int? pageNo, int recordSize, bool activeOnly, out int count, int? stockCheckCount = null)
{
var context = DataContextHelper.GetNewContext();
var products = context.Products
.Where(x => !x.IsDeleted && (!activeOnly || x.IsActive) && !x.Category.IsDeleted)
.AsQueryable();
if (!string.IsNullOrEmpty(searchTerm))
{
products = context.ProductRecords
.Where(x => !x.IsDeleted && x.Name.ToLower().Contains(searchTerm.ToLower()))
.Select(x => x.Product)
.Where(x => !x.IsDeleted && (!activeOnly || x.IsActive) && !x.Category.IsDeleted)
.AsQueryable();
}
if (categoryIDs != null && categoryIDs.Count > 0)
{
products = products.Where(x => categoryIDs.Contains(x.CategoryID));
}
}
基于@Rashik Hasnat 的回答,
我在访问 Name 属性时遇到问题,因为 Name 属性继承自 ProductRecords 模型,但表达式属性映射到 Products 模型。 你能帮忙解决这个问题吗? 谢谢你。
你可以像下面这样做:
代码如下所示:
if (!string.IsNullOrEmpty(searchTerm))
{
//split each word of the search string
var searchWordList = searchTerm.Split(" ");
var expression = context.ProductRecords
.Where(x => !x.IsDeleted && x.Name.ToLower().Contains(searchTerm.ToLower())).Select(x => x.Product)
.Where(x => !x.IsDeleted && (!activeOnly || x.IsActive) && !x.Category.IsDeleted);
foreach (var word in searchWordList)
{
// Add a condition for each word to be present
expression = expression
.Where(x => x.Name.ToLower().Contains(word.ToLower()));
}
products = expression
.AsQueryable();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.