我正在尝试在我的 ASP.NET MVC 网站中构建搜索。 例如,我想返回与搜索字符串中具有任何关键字匹配的项目相匹配的产品。举个例子,我有这样的产品,
- DC 12V RGB 5050 5M LED 灯条
- RGB 5050 LED 5 米灯带套件,带 24 键红外 Remote
- LED 灯带 DC 12V 44 键红外遥控 RGB Controller
目前,如果我搜索“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 的回答,
我在访问名称属性时遇到问题,因为名称属性继承自 ProductRecords 模型,但表达式属性映射到产品模型。您能帮忙解决这个问题吗?谢谢。
最佳答案
我更愿意在此处使用正则表达式,但不幸的是,在 LINQ to Entities 中使用它有一个限制。因此您可以使用 DbFunctions.Like() :
if (!string.IsNullOrEmpty(searchTerm))
{
// Build the pattern for the Like() method
var pattern = "%" + String.Join("%", searchTerm.Split(' ')) + "%";
products = context.ProductRecords
.Where(x => !x.IsDeleted && DbFunctions.Like(x.Name, pattern))
.Select(x => x.Product)
.Where(x => !x.IsDeleted && (!activeOnly || x.IsActive) && !x.Category.IsDeleted)
.AsQueryable();
}
关于c# - 按搜索字符串中的每个单词搜索名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68604843/