LINQ for LIKE queries of array elements

后端 未结 5 1345
臣服心动
臣服心动 2020-12-30 16:01

Let\'s say I have an array, and I want to do a LINQ query against a varchar that returns any records that have an element of the array anywhere in the varchar.

Somet

5条回答
  •  时光取名叫无心
    2020-12-30 16:32

    Unfortunately, LIKE is not supported in LINQ to SQL as per here:

    http://msdn.microsoft.com/en-us/library/bb882677.aspx

    To get around this, you will have to write a stored procedure which will accept the parameters you want to use in the like statement(s) and then call that from LINQ to SQL.


    It should be noted that a few of the answers suggest using Contains. This won't work because it looks to see that the entire string matches the array element. What is being looked for is for the array element to be contained in the field itself, something like:

    industry LIKE '%%'
    

    As Clark has mentioned in a comment, you could use a call to IndexOf on each element (which should translate to a SQL call):

    string[] industries = { "airline", "railroad" }
    
    var query = 
        from c in contacts 
        where
            c.industry.IndexOf(industries[0]) != -1 ||
            c.industry.IndexOf(industries[1]) != -1
    

    If you know the length of the array and the number of elements, then you could hard-code this. If you don't, then you will have to create the Expression instance based on the array and the field you are looking at.

提交回复
热议问题