c# - 按搜索字符串中的每个单词搜索名称

标签 c# asp.net asp.net-mvc entity-framework linq

我正在尝试在我的 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/

相关文章:

c# - MVC 6 VNext 如何从不同的区域设置相同的布局

c# - 使用WarpAffine()将Emgu.CV.Image向右移动

c# - 从磁盘号检索虚拟磁盘文件名

c# - 使用 propertyGrid 时出现 System.MissMethodException

asp.net - FluentSecurity 是取代 Asp.Net 成员(member)资格提供商还是应该与之互补/合作?

asp.net - 服务器.传输 Vs.响应.重定向

c# - 如何在 C# 中找到两个标记字符之间的可变长度字符串?

asp.net-mvc - 在MVC中使用Rotativa pdf显示动态标题

c# - 找不到对象 "dbo.Table",因为它不存在或您没有权限

c# - 在 .Net 4.5 中使用 async/await 编写多线程方法