views:

1947

answers:

6

Hi there,

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

+11  A: 

You can use SqlMethods.Like().

An example of the usage:

var results =
        from u in users
        where SqlMethods.Like(u.FirstName, "%John%")
        select u;
Ryan Versaw
very cool! didn't know that existed...
J.13.L
This will only work with LinqToSql queries (as should be apparent by the class used).
Ryan Versaw
Very nice, I didn't know that existed either +1
DoctaJonez
Wow, I never knew there was a SqlMethods class.
BFree
A: 
.Where( column LIKE "Pattern")
Rony
Fine for VB, but not C#.
Noldorin
A: 

Are you talking LINQ to objects or LINQ to SQL?

For LINQ to objects you'll have to resort to regular expressions me thinks.

fretje
A: 

not sure if you talk LinqToSql or just linq... but you could regular expressions like this:

.Where(dto => System.Text.RegularExpressions.Regex.IsMatch(dto.CustomerName, @"Ad"));
J.13.L
+4  A: 

add System.Data.Linq.SqlClient to your using or imports list then try:

var results= from x in data
             where SqlMethods.Like(x.SearchField, “%something%like%this%”)
             select x;
Joe Davis
+4  A: 

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);
}
David Basarab
Bit long winded - he could just use SqlMethods.Like
Chalkey
You are always assuming that you are calling a SQL database. What if you are query a list that was created in memory?
David Basarab
His question is tagged with SQL
Chalkey