检查集合是否为空

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)


man*_*ale 9

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

if (devices.Any())
{
   //devices is not empty
}
Run Code Online (Sandbox Code Playgroud)

  • Any()是LINQ方法,这样的简单检查会给您带来过多的开销。如果您的收藏集不IEnumerable,则首选插入计数或长度 (4认同)
  • @TOPKEK 如果是 `ICollection<TSource>` 或老式非通用 `ICollection` LINQs `Any()` 只是传递 count!=0 ,因此对于大多数用例来说,开销可以忽略不计(甚至是可优化的) IList 或数组。即使在“IIListProvider<TSource>”的情况下,它也会被计数,只有在便宜的情况下才会被计数,否则会执行单个 MoveNext - 因此比您的建议计数更快。TL;DR:没有理由不使用 `Any()`。 (2认同)

Chr*_*Way 7

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