43

How can i perform an LIKE query within Linq?

I have the following query i would like to execute.

var results = from c in db.costumers
              where c.FullName LIKE "%"+FirstName+"%,"+LastName
              select c;
Julien Hoarau
  • 47,315
  • 20
  • 124
  • 117
mweber
  • 443
  • 1
  • 4
  • 6

8 Answers8

42

Try using string.Contains () combined with EndsWith.

var results = from c in db.Customers
              where c.FullName.Contains (FirstName) && c.FullName.EndsWith (LastName)
              select c;
Kieron
  • 25,894
  • 15
  • 74
  • 118
42

You could use SqlMethods.Like(matchExpression,pattern)

var results = from c in db.costumers
              where SqlMethods.Like(c.FullName, "%"+FirstName+"%,"+LastName)
              select c;

The use of this method outside of LINQ to SQL will always throw a NotSupportedException exception.

Julien Hoarau
  • 47,315
  • 20
  • 124
  • 117
  • I didn't have time to monkey around with this : where SqlMethods.Like(s.Email, id + "%") that through an error (yes i have the using System.Data.Linq.SqlClient; , I changed to where s.Email.Contains(id) even though that is not the same, I can make it work with changing to EndsWith – Tom Stickel Oct 20 '15 at 17:29
  • 5
    For EF Core it's `Microsoft.EntityFrameworkCore.EF.Functions.Like(c.FullName, $"%{fullName}%")`. – Alternatex Aug 09 '18 at 12:02
18

Try like this

var results = db.costumers.Where(X=>X.FullName.Contains(FirstName)&&(X=>X.FullName.EndsWith(LastName))
                          .Select(X=>X);
Thorin Oakenshield
  • 13,382
  • 31
  • 102
  • 143
5

2019 is here:

Requires EF6

using System.Data.Entity;
string searchStr ="bla bla bla";
var result = _dbContext.SomeTable.Where(x=> DbFunctions.Like(x.NameAr, string.Format("%{0}%", searchStr ))).FirstOrDefault();
Adel Mourad
  • 1,123
  • 13
  • 10
  • not only EF6, required EF 6.2.0 https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.dbfunctions.like?view=entity-framework-6.2.0 – Wangsu Apr 09 '20 at 13:44
4
String [] obj = (from c in db.Contacts
                           where c.FirstName.StartsWith(prefixText)
                           select c.FirstName).ToArray();
            return obj;

StartsWith() and EndsWith() can help you a lot here. If you want to find data in between the field, then Contains() can be used.

Ali Haider
  • 407
  • 1
  • 5
  • 15
3
 where c.FullName.Contains("string")
Praveen Prasad
  • 30,761
  • 16
  • 70
  • 105
1

You can use contains:

string[] example = { "sample1", "sample2" };
var result = (from c in example where c.Contains("2") select c);
// returns only sample2
hwcverwe
  • 5,097
  • 7
  • 33
  • 58
0

var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();

User can use this of like query in Linq and fill the student model.