Curtis White
Curtis White

Reputation: 6353

How to use "contains" or "like" in a dynamic linq query?

The help file that came with Dynamic Linq in the CSharpSamples.zip does not show any examples of using contains or like.

Are there any simple workarounds for doing this? i.e where (col like @col) doesn't work.

Upvotes: 43

Views: 52927

Answers (3)

user2042930
user2042930

Reputation: 690

For me the solution was outerIt.

   class User { public string Name { get; set; } }
   ...
   IQueryable<User> query = db.Users;
   ...
   query = query.Where("@0.Contains(outerIt.Name)", list);

Note that outerIt is kind of a keyword built in the library (you don't need to modify it as you can read it in an answer here). You can access the property of your query's type through it.

Upvotes: 12

Curtis White
Curtis White

Reputation: 6353

Here is the answer! The Dynamic Linq does support the . operator,

According to the docs:

"Instance field or instance property access. Any public field or property can be accessed."

Thus, it is possible to use this syntax

.Where("MyColumn.Contains(@0)", myArray)

Thanks for all the suggestions! And thanks to me for finding the solution.

Upvotes: 66

spender
spender

Reputation: 120480

Actually, there is direct support for the like operator in Linq2Sql:

db.MyTable.Where(a => SqlMethods.Like(a.Name, "%"+searchTerm+"%"))

See here:

http://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods_members.aspx

... but I prefer using startsWith, endsWith and contains for most applications.

Upvotes: 4

Related Questions