简体   繁体   English

foreach中的条件LINQ查询

[英]Conditional LINQ query in foreach

I have a multiselection box and I would like to iterate over the selected items and do a linq query, but I'm not sure how to write it. 我有一个多选框,我想遍历所选项目并执行linq查询,但是我不确定如何编写它。 This is what I have so far: 这是我到目前为止的内容:

if (lbStateLegislation.Items.Count > 0)
{
  foreach (ListItem li in lbStateLegislation.Items)
    attributes = vdc.attributes.Where(a => a.fieldvalue == li.Value).ToList();
}

I basically need to construct an OR query, so it is selecting from the collection where there are values for each of the selected items. 我基本上需要构造一个OR查询,因此它是从集合中选择每个选定项都有值的地方。 I think, as it's written now, it is doing an AND query. 我认为,正如现在所写,它正在执行AND查询。

Just use the Contains extension method. 只需使用Contains扩展方法。 Linq2Sql will translate it as an IN clause: Linq2Sql会将其转换为IN子句:

var inValues = lbStateLegislation.Items.Select(s => s.Value);
vdc.attributes.Where(a => inValues.Contains(a.fieldvalue));

You may be able to combine the two statements into one, but I will leave that for you to try as I'm not positive that it will work as a single statement. 您可能可以将这两个语句合并为一个,但是我不愿意将其留给您尝试,因为我不确定它会作为一个单独的语句工作。

HTH 高温超导

var attributes=
  vdc.attributes.Where(q=> 
                   lbStateLegislation.Items.Any(o=> o.Value == q.fieldValue))
                 .Select(o=> o);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM