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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With