Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using contains with wildcard in Entity Framework Core [duplicate]

I would like to know if it is possible to do a wildcard search using LINQ.

I see LINQ has Contains, StartsWith, EndsWith, etc.

What if I want something like %Test if%it work%, how do I do it?

Regards

like image 778
PlayKid Avatar asked Nov 18 '22 05:11

PlayKid


2 Answers

You can use SqlMethods.Like().

An example of the usage:

var results =
        from u in users
        where SqlMethods.Like(u.FirstName, "%John%")
        select u;
like image 165
Ryan Versaw Avatar answered Dec 16 '22 00:12

Ryan Versaw


I would use Regular Expressions, since you might not always be using Linq to SQL.

Like this example of Linq to Objects

List<string> list = new List<string>();
list.Add("This is a sentence.");
list.Add("This is another one.");
list.Add("C# is fun.");
list.Add("Linq is also fun.");

System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex("This");

var qry = list
    .Where<string>(item => regEx.IsMatch(item))
    .ToList<string>();

// Print results
foreach (var item in qry)
{
    Console.WriteLine(item);
}
like image 33
David Basarab Avatar answered Dec 15 '22 22:12

David Basarab