Matheus Gelinski
Matheus Gelinski

Reputation: 508

Linq Query Where() SQL % equivalent

We can use the method .Contains(string) in a LINQ Expression, that sounds like '%search text%', method .StartsWith(string), that sounds like 'search text%', and method .EndsWith(string), that sounds like '%search text'.

But I need something that sounds '%search%text%', that finds all content containing 'search' and 'text', but not sequential.

Example: I have these records:

search my text

search for the text

seek the text

In SQL, the query with LIKE '%search%text%' brings:

search my text

search for the text

But not brings the 'seek the text'.

Any ideas?

Upvotes: 6

Views: 405

Answers (2)

ANewGuyInTown
ANewGuyInTown

Reputation: 6447

you could use something like this:

var rx = new Regex("search.*text", RegexOptions.IgnoreCase);
List<string> lists=new List<string>(){"search text","search this text","search my book"};
var result = lists.Where(x => rx.IsMatch(x));

If you getting input in the form of "search%text", then you could just string replace "%" with ".*" and use as Reg ex pattern.

Upvotes: 0

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

You can use one of the helper method:

var result = from o in ctx.table
where SqlMethods.Like(o.column, "%search%text%")
select o.column;

Upvotes: 7

Related Questions