public ActionResult Create(FormCollection collection, FormCollection formValue)
{
try
{
Project project = new Project();
TryUpdateModel(project, _updateableFields);
var devices = collection["devices"];
string[] arr1 = ((string)devices).Split(',');
int[] arr2 = Array.ConvertAll(arr1, s => int.Parse(s));
project.User = SessionVariables.AuthenticatedUser;
var time = formValue["Date"];
project.Date = time;
project.SaveAndFlush();
foreach (int i in arr2)
{
Device d = Device.Find(i);
d.Projects.Add(project);
d.SaveAndFlush();
}
return RedirectToAction("Index");
}
catch (Exception e)
{
return View(e);
}
}
我想将 foreach 包装在一个 if 语句中以检查是否
var devices = collection["devices"];
是否为空。如果它为空,则不应执行 for each。郑重声明,collection["devices"] 是表单中复选框值的集合。
最佳答案
您可以使用Count
字段来检查集合是否为空
所以你最终会得到这样的结果:
if(devices.Count > 0)
{
//foreach loop
}
关于c# - 检查集合是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3914346/