使用LINQ搜索关键字

如果我有一个包含标题的文本字段,并且我有一个关键字列表,我如何在标题中搜索(n)个关键字的标题?

因此,如果我的标题是“烤鸡肉,培根和韭菜馅饼”,并且用户搜索“鸡肉培根萝卜”,我想返回上述食谱。

基本上我想说,如果标题包含2个或更多的搜索词,那么它被认为是有效的,应该返回。 但如果它只包含1则忽略它。

理想情况下,我喜欢他们加权,以便更多的条款出现在列表中更高,但可能是版本2. 🙂

编辑

在这一点上我应该提一下,我希望这是原生的.net和c#。

做像Andras这样的文字索引可能是你最好的选择。 但要回答这个问题:您可以编写一个方法来自定义构建表达式树来表示一个选择器,该选择器为每个匹配的搜索关键字的属性添加1。 见下文:

 var entries = new[] { new Entry{ ID = 1, Title = "Baking a chicken, bacon and leek pie"} }.AsQueryable(); var search = "chicken bacon turnip"; var q = entries.Select(GetSelector(search)); var matches = q.Where(e => e.MatchCount > 1); public Expression> GetSelector(string search) { var searchWords = search.Split(new[] {' '}); // Rather than creating the selector explicitly as below, you'll want to // write code to generate this expression tree. Expression> selector = e => new EntryMatchCount { ID = e.ID, MatchCount = (e.Title.Contains(searchWords[0]) ? 1 : 0) + (e.Title.Contains(searchWords[1]) ? 1 : 0) + (e.Title.Contains(searchWords[2]) ? 1 : 0) }; return selector; } 

如果是我,我会做这样的事……

创建一个帮助类,它做两件事,拆分标题并根据关键字匹配返回一个分数….

 public static class Helper { public static int GetScore(string Title, params string[] keywords) { // your routine that calcs a score based on the matchs against the Title. } } then you can use a linq statement like.... var matches = from t in GetYourTitles let score = Helper.GetScore(t, keywordlist) where score >= 2 orderby score select t; 

AODBDataContext db = new AODBDataContext();

  var fItems = from item in db.Items where SqlMethods.Like(item.Name, l) where cats.Contains(item.ItemType) where item.QL >= minQL where item.QL <= maxQL select item;