.net 如何在动态 linq 查询中使用“包含”或“喜欢”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2455659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use "contains" or "like" in a dynamic linq query?
提问by Curtis White
The help file that came with Dynamic Linq in the CSharpSamples.zip does not show any examples of using contains or like.
CSharpSamples.zip 中 Dynamic Linq 附带的帮助文件没有显示任何使用 contains 或 like 的示例。
Are there any simple workarounds for doing this? i.e where (col like @col) doesn't work.
是否有任何简单的解决方法来执行此操作?即哪里(col like @col)不起作用。
回答by Curtis White
Here is the answer! The Dynamic Linq does support the . operator,
这是答案!动态 Linq 确实支持 . 操作员,
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.
感谢所有的建议!感谢我找到了解决方案。
回答by user2042930
For me the solution was outerIt.
对我来说,解决方案是externalIt。
class User { public string Name { get; set; } }
...
IQueryable<User> query = db.Users;
...
query = query.Where("@0.Contains(outerIt.Name)", list);
Note that outerItis 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.
请注意,outerIt是库中内置的一种关键字(您无需修改它,因为您可以在此处的答案中阅读它)。您可以通过它访问查询类型的属性。
回答by spender
Actually, there is directsupport for the like operator in Linq2Sql:
实际上,Linq2Sql 中直接支持 like 运算符:
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
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.
...但我更喜欢对大多数应用程序使用startsWith、endsWith 和contains。

