15
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.

mantal
  • 1,093
  • 1
  • 20
  • 38
Prd
  • 247
  • 1
  • 2
  • 12

6 Answers6

17

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
}
Manaf Abu.Rous
  • 2,397
  • 21
  • 24
  • Yeah I've actually tried that but it gives me an error: Error 1 'string' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) – Prd Oct 12 '10 at 12:04
  • Try Count() https://msdn.microsoft.com/en-us/library/vstudio/bb338038%28v=vs.100%29.aspx as I think FormCollection is IEnumerable – danio Feb 20 '15 at 09:51
  • 1
    if you are using a `IMongoCollection` you need to use `YourCollection.AsQueryable().Count() == 0` – Mauricio Gracia Gutierrez Apr 17 '23 at 01:37
15

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

if (devices.Any())
{
   //devices is not empty
}
mantal
  • 1,093
  • 1
  • 20
  • 38
  • 6
    Any() is a LINQ method and gives you too much overhead for such a simple check. Prefer Count or Length insted if your collection is not IEnumerable – TOP KEK Jul 06 '17 at 21:22
  • 2
    @TOPKEK in case of a `ICollection` or an old fashion non-generic `ICollection` LINQs `Any()` simply passes count!=0 through so the overhead is neglible (and even optimizable) for most use cases like IList or array. Even in case of an `IIListProvider` it gets count, only if cheap and otherwise does a single MoveNext - thus faster than your suggestion to count. TL;DR: there is no reason _not_ to use `Any()`. – mbx Oct 07 '22 at 06:00
  • if you are using a `IMongoCollection` you need to use `YourCollection.AsQueryable().Count() == 0` – Mauricio Gracia Gutierrez Apr 17 '23 at 01:38
10

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();
        }
    }
}
ChrisWay
  • 1,157
  • 16
  • 33
  • Yes i'm sorry im an idiot. Misread the error i got when trying a if statement. It wasn't being caused by the forearch trying to loop through an empty collection. putting the conversion to int array within the if statement solves it. – Prd Oct 12 '10 at 12:47
  • This is - pedantically - not the answer to the question in the title, but the best answer in terms of the problem the topic owner has put. No need to check emptyness in the first place ;-) Vote up from me. – Ingmar Feb 10 '23 at 07:38
1

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.

thecoop
  • 45,220
  • 19
  • 132
  • 189
  • its a formcollection. I am converting it to a int array so the values can be processed. Ive updated the code to show the entire action as it is now. This code works as long as you select at least 1 checkbox which is the problem. – Prd Oct 12 '10 at 12:27
  • formcollection only returns controls that contain data. that is normal behaviour – Roadie57 Oct 12 '10 at 12:34
0

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();
    }
}
mantal
  • 1,093
  • 1
  • 20
  • 38
Roadie57
  • 324
  • 1
  • 6
0

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(); 
}
Daniel Puiu
  • 962
  • 6
  • 21
  • 29