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.
source to share
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;
source to share
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
source to share