Search code examples
entity-frameworklinqsql-like

Using the like keyword with linq


Possible Duplicate:
How to do SQL Like % in Linq?

Im using mvc 3 and entity framework. How do i do a like search with linq or a lambda expression. Please assisst


Solution

  • Since the goal is for EF expressions to be parsed into SQL, where the LIKE predicate should be applied, there are at least 3 ways to do this, depending on where you want the % wildcard to be placed

    Starts With the Phrase

    C#:

    .Where(customer => customer.Name.StartsWith("Bloggs"))
    

    => SQL

     WHERE c.Name LIKE 'Bloggs%'
    
    Contains the Phrase

    C#:

    .Where(customer => customer.Name.Contains("Bloggs"))
    

    => SQL

    WHERE c.Name LIKE '%Bloggs%'
    
    Ends in the Phrase

    C#:

    .Where(customer => customer.Name.EndsWith("Bloggs"))
    

    => SQL

    WHERE c.Name LIKE '%Bloggs'
    

    Performance

    When applicable, for performance reasons, StartsWith should be preferred over the other two, given that it has a better chance of using an index on the column.

    LIKE %x% or LIKE %x will generally result in an index or table scan, unless an unusual index is created on the column.