Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if collection is empty or not

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.

like image 213
Prd Avatar asked Oct 12 '10 11:10

Prd


People also ask

How do you check if the collection is empty or not in Java?

The size() and isEmpty() of java. util. Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value.

Does collection isEmpty check for NULL?

isEmpty() doesn't check if a list is null . If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not.


2 Answers

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
}
like image 62
Manaf Abu.Rous Avatar answered Oct 01 '22 05:10

Manaf Abu.Rous


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

if (devices.Any())
{
   //devices is not empty
}
like image 23
mantal Avatar answered Oct 01 '22 07:10

mantal