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开发者_StackOverflow中文版 workarounds for doing this? i.e where (col like @col) doesn't work.
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.
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.
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.
精彩评论