动态 Linq 和未知数量的替换值?
通常,带有字符串的动态 linq 查询可以使用替换值,例如:
result =
db.Persons.Where("Name == @1", "John");
我想要将未知数量的字符串传递到 Where
子句中。我对整数没有问题,但 API 似乎无法处理没有替换值的字符串。
有谁知道解决这个问题的方法吗?我为 Where
语句创建了一个串联字符串,因此我可以添加“@1”或其他内容,但我无法向 Where()
添加参数,所以我陷入了困境。
谢谢!
Typically a dynamic linq query with string can use a substitution value such as:
result =
db.Persons.Where("Name == @1", "John");
I have an unknown number of strings that I want to pass into the Where
clause. I have no problem with integers, but the API cannot seem to handle a string without a substitution value.
Does anyone know a way around this? I created a concatenated string for my Where
statement, so I can add "@1" or whatever, but I cannot add parameters to the Where()
so I am stuck.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以。
Where
方法的第二个参数是params object[]values
,因此您只需传递一个对象数组即可。例如,假设您在字典中拥有属性名称和值,您可以执行以下操作:
Yes, you can. The second argument of the
Where
method isparams object[] values
, so you just need to pass an array of objects.For instance, assuming you have the property names and values in a dictionary, you could do something like this:
我想我明白你关于字符串替换问题的意思。
这里有几个可供探索的替代方案。 Thomas Petricek 的解决方案(如果您能理解的话)特别有趣:
在运行时用 C# 构建[动态] LINQ 查询
http://tomasp.net/articles/dynamic-linq-queries.aspx
使用 PredicateBuilder 动态组合表达式谓词
http://www.albahari.com/nutshell/predicatebuilder.aspx
另请参阅http://blogs.msdn.com/b/mattwar/archive /2006/05/10/594966.aspx
I think I can see what you mean about the string substitution problem.
Here are a couple of alternatives to explore. Thomas Petricek's solution, if you can follow it, is especially interesting:
Building [Dynamic] LINQ Queries at Runtime in C#
http://tomasp.net/articles/dynamic-linq-queries.aspx
Dynamically Composing Expression Predicates using PredicateBuilder
http://www.albahari.com/nutshell/predicatebuilder.aspx
See also http://blogs.msdn.com/b/mattwar/archive/2006/05/10/594966.aspx
我为此做了一些事情。将 David Fowlers DynamicLinq 项目与 PredicateBuilder 结合使用,您可以从 Generic IQueryable 构建谓词并构建它们。特别感谢 StackOverflow 的一些答案,它给了我这一行从
实现转换。
这允许“或”在这样的循环中加入通用谓词...
完整的文章是 此处,完整演示位于 MvcCms.CodePlex
I have made something for this. Using David Fowlers DynamicLinq project in combination with a PredicateBuilder you can build predicates from a Generic IQueryable and build them. Special thanks to some StackOverflow answer that gave me this line to convert from
Implmentation..
This allows "or" joining generic Predicates in a loop like this...
The full write up is here and the full demonstration is in the source at MvcCms.CodePlex