Using contains() in LINQ to SQL

后端 未结 7 1815
野性不改
野性不改 2020-11-27 05:39

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

7条回答
  •  面向向阳花
    2020-11-27 06:14

    You could try:

    public IQueryable SearchForParts(string[] query)
    {
        return from part in db.Parts
               where query.All(term => part.partName.Contains(term))
               select part;
    }
    

    However, I'm not sure if LINQ to SQL will be able to transform it into T-SQL. Another option would be:

    public IQueryable SearchForParts(string[] query)
    {
        var result = from part in db.Parts
                     select part;
    
        foreach(var term in query)
        {
            result = from part in result
                     where part.partName.Contains(term)
                     select part;
        }
    
        return result;
    }
    

    It's not as pretty, but it should work. You'll get a query with a lot of ANDs in the where clause.

提交回复
热议问题