I am building up a query in C#. For integer and string fields, case is quite simple. For date fields, I am using following query:
list.Where("myDateColumn >= DateTime(2017,1,20)");
How I can perform following SQL LIKE query in LINQ?
select * from table where myTextColumn LIKE '%abc%';
You can use Contains with myTextColumn
field
var date = new DateTime(2017,1,20);
list.Where(x => x.myDateColumn >= date && x.myTextColumn.Contains('abc'));
There are lots of possibilities for Like in Linq:
For LIKE '%abc%';
list.Where(x => x.myTextColumn.Contains('abc'));
For LIKE 'abc%';
list.Where(x => x.myTextColumn.StartWith('abc'));
For LIKE '%abc';
list.Where(x => x.myTextColumn.EndsWith('abc'));
Updates : If you need to add Date comparison as well means you can do like the following:
DateTime date2Compare = new DateTime(2017, 1, 20);
list.Where(x => myDateColumn >= date2Compare && x.myTextColumn.Contains('abc'));
Placement of the Wildcard '%' in a LIKE clause makes a difference, and C# has the methods to back this up. Below is what the placements of the Wildcard means.
LIKE '%abc'
Meaning: Find any word ending with 'abc'.
C# equivalent: EndsWith
LIKE 'abc%'
Meaning: Find any word starting with 'abc', and you don't care about the text after.
C# equivalent: StartWith
LIKE '%abc%'
Meaning: Find any word that contains 'abc', and you don't care where in the word it appears.
C# equivalent: Contains
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