在 LINQ to SQL 中使用 contains()

Using contains() in LINQ to SQL(在 LINQ to SQL 中使用 contains())
本文介绍了在 LINQ to SQL 中使用 contains()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 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 IQueryable<Part> SearchForParts(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 IQueryable<Part> SearchForParts(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" }

这篇关于在 LINQ to SQL 中使用 contains()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

LINQ to SQL query using quot;NOT INquot;(使用“NOT IN的 LINQ to SQL 查询)
How to do a full outer join in Linq?(如何在 Linq 中进行完整的外部联接?)
LINQ to SQL Web Application Best Practices(LINQ to SQL Web 应用程序最佳实践)
How do I group data in an ASP.NET MVC View?(如何在 ASP.NET MVC 视图中对数据进行分组?)
how to update the multiple rows at a time using linq to sql?(如何使用 linq to sql 一次更新多行?)
how to recognize similar words with difference in spelling(如何识别拼写不同的相似词)