[英]LINQ expression inside foreach loop
In my View() i have many checkboxes with attr name="types". 在我的View()中,我有许多带有attr name =“ types”的复选框。 In my ActionResult I have a List types like parameter, and I do foreach loop to search in List, each type ID and add a Where() filter in my LINQ expression.
在我的ActionResult中,我有一个类似参数的List类型,并且执行foreach循环以搜索List,每个类型ID并在LINQ表达式中添加Where()过滤器。 If I select many types, the return is only one result and dont all what i chose.
如果我选择许多类型,则返回的结果只是一种,而不是我选择的所有结果。 Look:
看:
[HttpPost]
public ActionResult Index(List<int> types) {
var variable = from s in MyViewModel select s;
foreach(var type in types) {
variable = variable.Where(x => x.TypesId == type);
}
return View(MyViewModel);
}
Is there another way to do this? 还有另一种方法吗?
Thank you!! 谢谢!!
variable = variable.Where(x => types.Contains(x.TypesId));
这应该为您提供所有值,如果只需要一个,请在末尾添加.FirstOrDefault()
There are few problems in your code, no matter what other part of code do your return statement always returns all MyViewModel
collection. 您的代码中几乎没有问题,无论代码的其他什么部分,您的return语句始终返回所有
MyViewModel
集合。
Other problem is your code overwrite variable
inside the loop. 另一个问题是循环中的代码将覆盖
variable
。
I think, this is what you need. 我认为,这就是您所需要的。
return View(MyViewModel.Select(s=> types.Any(t=>t.type == s.TypesId));
make attr name from name="types" to name="types[]" 将属性名称从name =“ types”更改为name =“ types []”
and it will post array of selected values 它将发布选定值的数组
The variable
is being reset each foreach
iteration. 的
variable
正在重置每个foreach
迭代。 Create a List
and add to it in foreach
block. 创建一个
List
并将其添加到foreach
块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.