动态LINQ和未知数量的替代价值? [英] Dynamic Linq and substitution values with unknown number?

查看:180
本文介绍了动态LINQ和未知数量的替代价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常用字符串动态LINQ查询可以使用一个替代值,如:

 的结果=
    db.Persons.Where(姓名== @ 1,约翰);
 

我有数目不详的,我想通过进入其中,子句的字符串。我有一个整数没有问题,但是API似乎无法处理的字符串不包含替换值。

有谁知道解决的办法?我创建了一个连接字符串,为我的其中,语句,因此我可以添加@ 1或什么,但我不能添加参数其中() 让我坚持。

谢谢!

解决方案
  

我创建一个连接字符串,我在这里发言,因此我可以添加@ 1或什么,但我不能添加参数凡(),所以我卡住了。

是的,你可以。在其中,方法的第二个参数是 params对象[]值,所以你只需要通过对象的数组

例如,假设你有一本字典的属性名称和值,你可以做这样的事情:

  VAR DIC =新字典<字符串,对象>
{
    {姓名,约翰},
    {年龄,30},
    {城市,纽约}
};

...

VAR条件= dic.Keys.Select(
    (键,IDX)=>
        的String.Format({0} == @ {1}键,IDX));
字符串predicate =的string.join(与条件);
对象[]值= dic.Values​​.ToArray();
结果= db.Persons.Where(predicate,价值观);
 

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!

解决方案

I creating 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.

Yes, you can. The second argument of the Where method is params 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:

var dic = new Dictionary<string, object>
{
    { "Name", "John" },
    { "Age", 30 },
    { "City", "New York" }
};

...

var conditions = dic.Keys.Select(
    (key, idx) =>
        string.Format("{0} == @{1}", key, idx));
string predicate = string.Join(" And ", conditions);
object[] values = dic.Values.ToArray();
result = db.Persons.Where(predicate, values);

这篇关于动态LINQ和未知数量的替代价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆