检查集合是否为空

发布于 2024-09-27 06:30:19 字数 980 浏览 7 评论 0原文

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"];

为空。如果其为空,则不应执行 foreach。根据记录,collection["devices"] 是表单中复选框值的集合。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

同展鸳鸯锦 2024-10-04 06:30:19

您可以使用 Count 字段来检查集合是否为空,

这样您最终会得到如下结果:

if(devices.Count > 0)
{
   //foreach loop
}

You can use the Count field to check if the collection is empty or not

so you will end up with something like this :

if(devices.Count > 0)
{
   //foreach loop
}
〆一缕阳光ご 2024-10-04 06:30:19

您可以使用方法 Any 来了解集合是否为任意元素。

if (devices.Any())
{
   //devices is not empty
}

You can use the method Any to know if a collection as any element.

if (devices.Any())
{
   //devices is not empty
}
空袭的梦i 2024-10-04 06:30:19

您不需要检查集合是否为空,如果为空,则 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();
        }
    }
}

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();
        }
    }
}
猫性小仙女 2024-10-04 06:30:19

按照目前的情况,您的代码将无法工作,正如您所说的 collection["devices"] 是复选框值的集合,但您却将其转换为 string< /代码>。您的意思是 collection 是复选框值吗? 集合的确切类型是什么?

任何实现了 ICollectionICollection 的对象都可以通过检查 Count 属性是否大于零来检查它是否为空。

Your code, as it stands, won't work, as you say that collection["devices"] is a collection of checkbox values, and yet you're casting it to a string. Do you mean collection is the checkbox values? What is the exact type of collection?

Any object that implements ICollection or ICollection<T> can be checked whether it's empty or not by checking if the Count property is greater than zero.

孤千羽 2024-10-04 06:30:19

如何检查数组长度

if (arr2.length > 0)
{
    foreach (int i in arr2)
    {
        Device d = Device.Find(i);
        d.Projects.Add(project);
        d.SaveAndFlush();
    }
}

How about checking the array length

if (arr2.length > 0)
{
    foreach (int i in arr2)
    {
        Device d = Device.Find(i);
        d.Projects.Add(project);
        d.SaveAndFlush();
    }
}
酒绊 2024-10-04 06:30:19

这在 Dot Net Core 中对我有用,但仅适用于模型的 IEnumerable,而不是实体
(我从 AutoMapper 得到了一些帮助)

将其转换为列表,然后检查容量

IEnumerable<vwPOD_Master> podMasters = _podRepository.GetNewPods(PartNumber);

IEnumerable<NewPODsDTO> podList = Mapper.Map<IEnumerable<NewPODsDTO>>(podMasters);

if (((List<NewPODsDTO>)podList).Capacity == 0) {
    return NotFound(); 
}

This worked for me in Dot Net Core but only for IEnumerable of Models not Entities
(I got a bit of help from AutoMapper)

Cast it as a List then check the Capacity

IEnumerable<vwPOD_Master> podMasters = _podRepository.GetNewPods(PartNumber);

IEnumerable<NewPODsDTO> podList = Mapper.Map<IEnumerable<NewPODsDTO>>(podMasters);

if (((List<NewPODsDTO>)podList).Capacity == 0) {
    return NotFound(); 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文