检查集合为空或不 [英] Check if collection is empty or not

查看:145
本文介绍了检查集合为空或不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中,检查是否

I want to wrap the foreach in a if statement which checks if

var devices = collection["devices"];

为空或不是。如果它的每个空的,不应被执行。根据记录,收集[设备]是复选框值的集合,从一种形式。

is empty or not. If its empty the for each should not be executed. For the record, collection["devices"] is a collection of checkbox values from a form.

推荐答案

您不需要检查,如果集合为空,如果是空的ForEach内code将不会被执行,看我下面的例子

You do not need to check if the collection is empty, if it is empty the code inside the ForEach will not be executed, see my example below.

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();
        }
    }
}

这篇关于检查集合为空或不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆