Extrakun
Extrakun

Reputation: 19305

Using LINQ with wildcard characters without using SqlMethods

I need to match certain string with wildcards, pretty much like with SQL LIKE. While there are similar questions on this topic, I am using Unity3D and while its Mono.NET library has LINQ, it doesn't have SqlMethods.

I would need to a way to emulate all the wild card characters. So '*MSB' should be able to match EastMSB, WestMSB, and DB0?-?? should match 'DB01-11', 'DB01-07' and etc.

Upvotes: 0

Views: 469

Answers (2)

RePierre
RePierre

Reputation: 9566

Linq is able to expand methods of System.String class like Contains into appropriate SQL queries so, the following query:

var data = dataContext.Clients.Where(c => c.Name.Contains("John"));

would be "translated" into something like:

DECLARE @p0 VarChar(1000) = '%John%'
SELECT [t0].[Id], [t0].[Name]
FROM [Clients] as [t0]
WHERE [t0].[Name] LIKE @p0

At least, this is what I am getting using LinqPad.

Upvotes: 3

Randy Minder
Randy Minder

Reputation: 48402

You could do something like this. The syntax may not be exactly correct, it's off the top of my head, but it will get you close.

List<string> list = new List<string>();
list.Add("#1");
list.Add("#2");
list.Add("#3");

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

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

Of course, the expression you pass in the Regex() constructor can be anything needed to satisfy your search.

Upvotes: -1

Related Questions