Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SQL LIKE operator in C# LINQ

Tags:

c#

sql

linq

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%';
like image 318
Behzad Qureshi Avatar asked Jan 20 '17 06:01

Behzad Qureshi


3 Answers

You can use Contains with myTextColumn field

var date = new DateTime(2017,1,20);
list.Where(x => x.myDateColumn >= date  && x.myTextColumn.Contains('abc'));
like image 92
Satpal Avatar answered Oct 19 '22 12:10

Satpal


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'));
like image 38
sujith karivelil Avatar answered Oct 19 '22 11:10

sujith karivelil


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

like image 7
monstertjie_za Avatar answered Oct 19 '22 12:10

monstertjie_za