【问题标题】:Check if collection is empty or not检查集合是否为空
【发布时间】:2011-04-24 06:46:12
【问题描述】:
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 的 if 语句中

var devices = collection["devices"];

是否为空。如果它为空,则不应执行 for each。作为记录,collection["devices"] 是表单中复选框值的集合。

【问题讨论】:

    标签: c# asp.net-mvc collections


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      检查数组长度怎么样

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

      【讨论】:

      • 那么 var devices 没有返回您期望的类型。
      • 如果人们不使用var,大多数人会更快乐……
      【解决方案3】:

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

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

      【讨论】:

      • Any() 是一种 LINQ 方法,对于这样一个简单的检查,它会给您带来太多开销。如果您的集合不是 IEnumerable,则首选 Count 或 Length insted
      【解决方案4】:

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

      【讨论】:

      • 是的,对不起,我是个白痴。误读了我在尝试 if 语句时遇到的错误。这不是由 forarch 试图遍历一个空集合引起的。将转换为 int 数组放在 if 语句中即可解决。
      【解决方案5】:

      就目前而言,您的代码不起作用,因为您说collection["devices"] 是复选框值的集合,但您将其转换为string。你的意思是collection 是复选框值吗? collection 的具体类型是什么?

      任何实现ICollection 或ICollection&lt;T&gt; 的对象都可以通过检查Count 属性是否大于零来检查它是否为空。

      【讨论】:

      • 它是一个表单集合。我将它转换为一个 int 数组,以便可以处理这些值。我已经更新了代码以显示现在的整个操作。只要您选择了至少 1 个问题所在的复选框,此代码就可以工作。
      • formcollection 只返回包含数据的控件。这是正常行为
      【解决方案6】:

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

      所以你最终会得到这样的结果:

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

      【讨论】:

      • 是的,我实际上已经尝试过了,但它给了我一个错误:错误 1 ​​'string' 不包含 'Count' 的定义,并且没有扩展方法 'Count' 接受类型的第一个参数'可以找到 string'(您是否缺少 using 指令或程序集引用?)
      • 试试 Count() msdn.microsoft.com/en-us/library/vstudio/… 因为我认为 FormCollection 是 IEnumerable
      猜你喜欢
      • 2016-06-20
      • 2017-05-28
      • 2017-05-07
      • 2018-08-09
      • 2021-11-02
      • 1970-01-01
      • 2013-06-19
      • 2016-03-28
      • 2012-02-28
      相关资源
      最近更新 更多