Partial string matching in LINQ

Consider the following SQL statement -

SELECT * FROM Customers WHERE FirstName LIKE '%IS%'

      

It will be looking for clients with "IS" as part of the name, right?

I like the same statement as in LINQ -

var names = from cust in customers where cust.FirstName ......

      

I cannot specify this condition. Can someone help me solve this.

Thank you for sharing your time and wisdom.

+3


source to share


3 answers


Most LINQ -> SQL translators will take a few regular methods from C # and translate them to SQL. Contains a very common method for translating and working with linq2sql and EF

var names = from cust in customers 
            where cust.FirstName.Contains("IS")
            select cust;

      



EDIT: (case insensitive)

var names = from cust in customers 
            where cust.FirstName.ToLower().Contains("is")
            select cust;

      

+7


source


For the insenstive case, contains

you can either convert the string to the same case (lower or upper), or better if you can use String.IndexOf Method (String, StringComparison)

var names = from cust in customers 
            where cust.FirstName.IndexOf("IS",StringComparison.InvariantCultureIgnoreCase) >= 0
            select cust;

      



While the performance gain may be negligible from this method, it will provide a correct case-insensitive comparison. It's always a good StringComparison

idea to use enum for case-insensitive string comparisons. You can see: The Turkish problem and why you should care

+2


source


Try the following:

var names = from cust in customers where cust.FirstName.Contains("IS")

      

+1


source







All Articles