问题描述
我正在尝试使用 linq-to-sql 在应用程序中实现一个非常基本的关键字搜索.我的搜索词在一个字符串数组中,每个数组项都是一个词,我想找到包含搜索词的行.我不介意它们包含的不仅仅是搜索词(很可能会),但所有搜索词都必须存在.
i'm trying to implement a very basic keyword search in an application using linq-to-sql. my search terms are in an array of strings, each array item being one word, and i would like to find the rows that contain the search terms. i don't mind if they contain more than just the search terms (most likely, they will), but all the search terms do have to be present.
理想情况下,我想要类似于以下代码段的内容,但我知道这行不通.另外,我在这里查看了这个问题,但该问题的作者似乎满足于以相反的方式做事( query.contains(part.partname) ),这对我不起作用.
ideally, i would like something similar to the snippet below, but i know that this won't work. also, i have looked at this question here, but the author of that question seems content to do things the other way round ( query.contains(part.partname) ), which doesn't work for me.
public iqueryablesearchforparts(string[] query) { return from part in db.parts where part.partname.contains(query) select part; }
我怎样才能重写这个查询,使它能够满足我的需要?
how can i rewrite this query so that it will do what i need?
推荐答案
看到其他尝试让我很难过 :(
looking at the other attempts saddens me :(
public iqueryablesearchforparts(string[] query) { var q = db.parts.asqueryable(); foreach (var qs in query) { var likestr = string.format("%{0}%", qs); q = q.where(x => sqlmethods.like(x.partname, likestr)); } return q; }
假设:
partname 看起来像:abc 123 xyz"
partname looks like: "abc 123 xyz"
查询是 { "abc", "123", "xy" }
query is { "abc", "123", "xy" }