Prd*_*Prd 9 c# collections asp.net-mvc
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想将foreach包装在if语句中,检查是否
var devices = collection["devices"];
Run Code Online (Sandbox Code Playgroud)
是空的.如果它为空,则不应执行每个.对于记录,集合["devices"]是表单中复选框值的集合.
Man*_*ous 14
您可以使用该Count字段检查集合是否为空
所以你最终得到这样的东西:
if(devices.Count > 0)
{
//foreach loop
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该方法Any来了解集合是否为任何元素.
if (devices.Any())
{
//devices is not empty
}
Run Code Online (Sandbox Code Playgroud)
您不需要检查集合是否为空,如果它是空的,ForEach中的代码将不会被执行,请参阅下面的示例.
using System;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main(string[] args)
{
List<string> emptyList = new List<string>();
foreach (string item in emptyList)
{
Console.WriteLine("This will not be printed");
}
List<string> list = new List<string>();
list.Add("item 1");
list.Add("item 2");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45364 次 |
| 最近记录: |