Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using contains() in 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.

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?

like image 377
a_m0d Avatar asked Mar 03 '10 05:03

a_m0d


People also ask

How use contains in LINQ?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

Can we use contains in SQL?

CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types. CONTAINS can search for: A word or phrase. The prefix of a word or phrase.

How do you check if a word contains in a string in SQL?

Method 1 - Using CHARINDEX() function This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero).

How can I use SQL like in LINQ?

In LINQ to SQL, we don't have a LIKE operator, but by using contains(), startswith(), and endswith() methods, we can implement LIKE operator functionality in LINQ to SQL.


1 Answers

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; } 

Assumptions:

  • partName looks like: "ABC 123 XYZ"

  • query is { "ABC", "123", "XY" }

like image 107
leppie Avatar answered Sep 28 '22 18:09

leppie