代码之家  ›  专栏  ›  技术社区  ›  Alon Gubkin

使用Linq到SQL的简单搜索

  •  3
  • Alon Gubkin  · 技术社区  · 14 年前

    什么是 问题 有了这个问题,我该怎么办 是吗?

    public JsonResult Find(string q)
    {
        var k = new List<string>(q.Split(' '));
    
        return Json(_dataContext.Jobs
            .OrderBy(p => new List<string>(p.Keywords.Split(' ')).Where(n => k.Contains(n)).Count())
            .Select(p => new { p.Title, p.IsFullTime, p.Location, p.Category, p.Url, p.Id }),
            JsonRequestBehavior.AllowGet);
     }
    

    '方法'系统字符串[]拆分(Char[])' 没有支持的到SQL的转换。

    q Keywords 对于每一行,共享的单词越多,顺序就越高。

    顺便说一句: 如果可能的话Lucene.NET网站为了改进这段代码,我很高兴看到一个简短的示例:)

    3 回复  |  直到 14 年前
        1
  •  2
  •   James Curran    14 年前

    .OrderBy(p=>新列表(p。关键词.拆分(' ')).

    嗯,这个信息很清楚。字符串。拆分()无法转换为SQL。

    在一个linqtosql语句中没有真正好的方法来实现这一点。我建议使用L2S提取数据,将其放入列表中,然后在那里对其进行排序。

        var jobs  = from p in _dataContext.Jobs
        select new 
          {
            p.Title,
            p.IsFullTIme,
            p.Location,
            p.Category,
            p.Url,
            p.Id,
            p.Keywords
          }
    
          return Json(job.ToList()
                .OrderBy(p=>p.Keywords.Split(' ').Where(n=>k.Contains(n)).Count()),
                 JsonRequestBehavior.AllowGet);
    

    然而,你真正的问题是你有一个非常糟糕的设计。正确的第三范式将有一个JobKeywords表(int JobId,varchar Keyword),其中一行是 每个 工作的关键字。然后可以在一个sql语句中完成:

     return Json(from p in _dataContext.Jobs     
                 order by p.Keywords.Intersect(k).Count()
                 select new { p.Title, p.IsFullTime, p.Location, 
                              p.Category, p.Url, p.Id },     
            JsonRequestBehavior.AllowGet);            
    
        2
  •  1
  •   Timwi    14 年前

    public JsonResult Find(string q)
    {
        var k = q.Split(' ');
    
        return Json(_dataContext.Jobs
            // Select all the columns we need, including Keywords
            // (still in SQL-land)
            .Select(p => new { p.Title, p.IsFullTime, p.Location, p.Category,
                               p.Url, p.Id, p.Keywords })
            // Move into C#-land
            .AsEnumerable()
            // Do the sorting here in C#-land
            .OrderBy(p => p.Keywords.Split(' ').Count(n => k.Contains(n)))
            // Finally, remove the Keywords column we no longer need
            .Select(p => new { p.Title, p.IsFullTime, p.Location, p.Category,
                               p.Url, p.Id }),
            JsonRequestBehavior.AllowGet);
     }
    

    整个的 每次作业表,即使添加 .Take(n) 在最后只得到顶端 n 条目。

        3
  •  0
  •   Mark Cidade    14 年前

    你不能使用 p.Keywords.Split(' ') . linqtosql不支持它。你为什么要按单子订购?