【问题标题】:Linq to SQL for search query用于搜索查询的 Linq to SQL
【发布时间】:2014-01-03 04:15:40
【问题描述】:

我需要做一个简单的搜索引擎。我找到了这个Microsoft example 来帮助我开始。现在,我的问题是在 linq to sql 中编写这个函数,这样我就可以在我的 dbcontext 应用程序中使用它。

/// <summary>
/// Search records from database.
/// </summary>
/// <param name="keywords">the list of keywords</param>
/// <returns>all found records</returns>
public List<Article> Search(List<string> keywords)
{
    // Generate a complex Sql command.
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.Append("select * from [Articles] where ");
    foreach (string item in keywords)
    {
        sqlBuilder.AppendFormat("([Title] like '%{0}%' or [Content] like '%{0}%') and ", item);
    }

    // Remove unnecessary string " and " at the end of the command.
    string sql = sqlBuilder.ToString(0, sqlBuilder.Length - 5);

    return QueryList(sql);
}

我在前面的基础上创建了自己的函数:

public List<Record> Search(string[] keywords)
{
    var result = (from c in _context.Tenders
                    where keywords.Contains(c.Title) || keywords.Contains(c.Summary)
                    select new Record()
                    {
                        Id = c.Id,
                        Title = c.Title,
                        Content = c.Summary
                    }).ToList();

    return result;
}

但是搜索结果不一样。如果我在 New contract in town 中搜索 Contract,我不会得到结果。我需要写完整的句子才能得到它。你能帮我指出我的 linq to sql 函数中缺少什么来实现这一点吗?

非常感谢!!

【问题讨论】:

    标签: c# sql linq entity-framework


    【解决方案1】:

    您很接近,keywords.Contains(c.Title) 正在请求与标题完全匹配。你需要做的是将它翻转过来。

    public List<Record> Search(string[] keywords)
    {
        var result = (from c in _context.Tenders
                      where keywords.Any(w => c.Title.Contains(w)) || keywords.Any(w => c.Summary.Contains(w))
                      select new Record()
                      {
                          Id = c.Id,
                          Title = c.Title,
                          Content = c.Summary
                      }).ToList();
    
        return result;
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用keywords.Any(w =&gt; c.Title.Contains(w)||c.Summary.Contains(w))的条件

      这将检查标题或摘要是否包含任何关键字

      var result = (from c in _context.Tenders
                   where keywords.Any(w => c.Title.Contains(w)||c.Summary.Contains(w))
                   select new Record()
                   {
                       Id = c.Id,
                       Title = c.Title,
                       Content = c.Summary
                   }).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-10
        • 2015-01-19
        • 1970-01-01
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多