c# - 检查集合是否为空

标签 c# asp.net-mvc collections

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/

相关文章:

c# - 将 db 对象发送到新线程的类

c# - NHibernate 4 升级 - 不能同时获取多个包

c# - 将 ListBox.items 转换为通用列表的最简洁方法

c# - 处理Control +在C#中输入多行文本框

c# - Xamarin Forms Android 出 java.lang.OutOfMemoryError 异常

javascript - Jquery 数据表 : Filter/Search based on select box outside the table

c# - 如何获取当前用户,以及如何在 MVC5 中使用 User 类?

asp.net-mvc - 如何防止ASP.NET MVC中的JSON序列化?

使用泛型类型或接口(interface)的 C# 集合

node.js - Express js中用户登录时如何更新token?