Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial string matching in LINQ

Tags:

linq

c#-4.0

Consider following SQL statement -

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

This is will search for customers having 'IS' as part of first name, right?

I like the same statement to be in LINQ -

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

I am unable to specify that condition. Can anybody help me out solve this.

Thanks for sharing your time and wisdom.

like image 537
IrfanRaza Avatar asked Dec 05 '25 17:12

IrfanRaza


2 Answers

Most LINQ -> SQL translators will take a few regular methods from c# and translate them into SQL. Contains is a very common method to translate and works 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;
like image 133
Not loved Avatar answered Dec 08 '25 16:12

Not loved


For Case insenstive contains, you can either convert the string to same case (lower or upper) or its 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;

Although the performance gain may be negligible from this method, but it will ensure a proper case insensitive comparison. Its always a good practice to use StringComparison enum for case insensitive string comparison. You may see: The Turkish İ Problem and Why You Should Care

like image 24
Habib Avatar answered Dec 08 '25 15:12

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!